package com.ruoyi.patient.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.patient.entity.*;
import com.ruoyi.patient.entity.order.*;
import com.ruoyi.patient.utils.*;
import com.ruoyi.service.domain.*;
import com.ruoyi.service.entity.pay.WxPayRespVO;
import com.ruoyi.service.entity.pay.WxPayV3Bean;
import com.ruoyi.service.mapper.*;
import com.ruoyi.service.service.IServiceAppinfoService;
import com.ruoyi.service.utils.WXPayUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ruoyi.patient.utils.SignGenerator.sortMap;
import static com.ruoyi.patient.utils.phpSecret.phpSign;

@Component
public class PatientOrderService {

    @Autowired
    private ServiceOrdersMapper ordersMapper;

    @Autowired
    private ServiceMycartMapper mycartMapper;

    @Autowired
    private ServiceItemscomboMapper itemscomboMapper;

    @Autowired
    private ServiceComboMapper comboMapper;

    @Autowired
    private ServiceItemsMapper itemsMapper;

    @Autowired
    private ServiceAddressMapper addressMapper;

    @Autowired
    private ServiceServedMapper servedMapper;

    @Autowired
    private ServicePayroadMapper payroadMapper;

    @Autowired
    private ServiceOrderscomboMapper orderscomboMapper;

    @Autowired
    private ServiceOrdersitemsMapper ordersitemsMapper;

    @Autowired
    private ServicePackagescomboMapper packagescomboMapper;

    @Autowired
    private ServicePackagesMapper packagesMapper;

    @Autowired
    private ServiceOrderspackagesMapper orderspackagesMapper;

    @Autowired
    private ServicePayMapper payMapper;

    @Autowired
    private ServiceAssessmentMapper assessmentMapper;

    @Autowired
    private ServicePictureMapper pictureMapper;

    @Autowired
    private ServiceCodeMapper codeMapper;

    @Autowired
    private ServiceTimeMapper timeMapper;

    @Autowired
    private ServiceActionMapper actionMapper;

    @Autowired
    private ServiceCancelorderreasonMapper cancelorderreasonMapper;

    @Autowired
    private ServiceCancelorderMapper cancelorderMapper;

    @Autowired
    private ServiceNurseMapper nurseMapper;

    @Autowired
    private ServiceOrdernurseMapper ordernurseMapper;

    @Autowired
    private ServiceOrderotherpayMapper orderotherpayMapper;

    @Autowired
    private ServiceUsersMapper usersMapper;

    @Qualifier("patientRestTemplate")
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IServiceAppinfoService appinfoService;

    @Autowired
    private ServiceMsginfoMapper msginfoMapper;

    @Autowired
    private ServiceUsermsgMapper usermsgMapper;

    @Autowired
    private WxPayV3Bean wxPayV3Bean;


    @Transactional
    public List<ItemComboReturn> initOrder(LoginPatient oldPatient)
    {
        List<ItemComboReturn> retItemComboPackage = new ArrayList<ItemComboReturn>();
        try {
            List<ServiceMycart> mycarts = mycartMapper.selectServiceMycartByMycartUserId(oldPatient.getUserId());
            for (ServiceMycart mycart : mycarts) {
                ItemComboReturn retNode = new ItemComboReturn();
                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(mycart.getMycartItemid());
                if (itemscombo == null)  continue;
                ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
                retNode.setItem(item);
                ServiceItemscombo searchItemsCombo = new ServiceItemscombo();
                searchItemsCombo.setItemscomboItemid(item.getItemId());
                List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectServiceItemscomboList(searchItemsCombo);
                ArrayList<ComboPackageReturn> retChlComboList = new ArrayList<>();
                for (ServiceItemscombo itemCombo : itemscomboList){
                    ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemCombo.getItemscomboSuppliesid());

                    ServicePackagescombo searchPackagesCombo = new ServicePackagescombo();
                    searchPackagesCombo.setPackagescomboComboid(combo.getComboId());
                    List<ServicePackagescombo> packagescomboList = packagescomboMapper.selectServicePackagescomboList(searchPackagesCombo);
                    ComboPackageReturn newChlNode = new ComboPackageReturn();
                    ArrayList<ServicePackages> packagesList = new ArrayList<>();
                    for (ServicePackagescombo packagescombo : packagescomboList) {
                        ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
                        packagesList.add(packages);
                    }
                    newChlNode.setPackages(packagesList);
                    newChlNode.setCombo(combo);
                    retChlComboList.add(newChlNode);
                }
                retNode.setComboPackages(retChlComboList);
                retItemComboPackage.add(retNode);

            }
            return retItemComboPackage;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public Page<PatientOrderReturnVO> getOrderList(String labelStatus, int page, int size, LoginPatient oldPatient)
    {
        List<PatientOrderReturn> retOrderList = new ArrayList<PatientOrderReturn>();
        List<PatientOrderReturnVO> retOrderListVO = new ArrayList<PatientOrderReturnVO>();
        try {
            ServiceOrders searchOrder = new ServiceOrders();
            searchOrder.setOrderUserid(oldPatient.getUserId());
            searchOrder.setOrderDelFlag("0");

            pictureMapper.selectServicePictureByPictureId(1L);

            Long[] orderServiceFlags = null;
            if (labelStatus.equals("unpaid")){
                searchOrder.setOrderUseFlag("1");
                orderServiceFlags = new Long[]{1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L};
            } else if (labelStatus.equals("unserved")) {
                orderServiceFlags = new Long[]{5L,6L,7L,8L};
            } else if (labelStatus.equals("serving")) {
                orderServiceFlags = new Long[]{9L,10L};
            } else if (labelStatus.equals("unsettled")) {
                orderServiceFlags = new Long[]{11L,12L,13L};
            }else if (labelStatus.equals("settled")){
                orderServiceFlags = new Long[]{14L,15L,16L,17L};
            }else {
                orderServiceFlags = new Long[]{1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L};
            }

            List<ServiceOrders> ordersList = new ArrayList<ServiceOrders>();
            for (Long flag : orderServiceFlags) {
                searchOrder.setOrderServiceflag(Math.toIntExact(flag));
                ordersList.addAll(ordersMapper.selectServiceOrdersList(searchOrder));
            }
            ordersList.sort(Comparator.comparing(ServiceOrders::getOrderCreatetime).reversed());

            for (ServiceOrders order : ordersList) {
                List<ItemComboReturn> retItemComboPackage = new ArrayList<ItemComboReturn>();
                PatientOrderReturn retOrderNode = new PatientOrderReturn();
                PatientOrderReturnVO retOrderVONode = new PatientOrderReturnVO();
                Long prePaid = 0L;

                retOrderNode.setOrder(order);//订单信息
                retOrderVONode.init(order);

                ServicePay payInfo = payMapper.selectServicePayByPayId(order.getOrderPay());
                if(payInfo != null) retOrderNode.setServicePay(payInfo);//支付信息
                if(payInfo != null) retOrderVONode.initPay(payInfo);

                ServiceCode code = codeMapper.selectServiceCodeByOrderId(order.getOrderId());
                if(code != null) retOrderNode.setCode(code.getCodeCode());//验证码
                if(code != null) retOrderVONode.setVerifiCode(code.getCodeCode());

                List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(order.getOrderId());
                for (ServiceOrderscombo orderscombo : orderscomboList) {
                    PatientOrderInfo retVONode = new PatientOrderInfo();
                    ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(orderscombo.getOrderscomboComboid());
                    ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
                    ServiceCombo combo = comboMapper.selectServiceComboByComboIdNew(orderscombo.getOrderscomboComboid());
                    retVONode.initItem(item);//项目信息录入
                    Long price = 0L;
                    retVONode.setSpecId(combo.getComboId());
                    retVONode.setSpecName(combo.getComboName());
                    retVONode.setCount(orderscomboList.get(0).getOrderscomboCount());
                    price += combo.getComboPrice();

                    List<ServicePackagescombo> packagescombos = packagescomboMapper.selectServicePackagescomboByComboId(combo.getComboId());
                    for (ServicePackagescombo packagescombo : packagescombos) {
                        ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
                        ServiceOrderspackages searchOrdersPackages = new ServiceOrderspackages();
                        searchOrdersPackages.setOrderspackagesOrderid(order.getOrderId());
                        searchOrdersPackages.setOrderspackagesPackageid(packages.getPackagesId());
                        searchOrdersPackages.setOrderspackagesDelFlag("0");
                        List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(searchOrdersPackages);
                        if (orderspackagesList.size() > 0) {
                            retVONode.setPkgId(packages.getPackagesId());
                            retVONode.setPkgName(packages.getPackagesName());
                            price += packages.getPackagesPrice();
                            break;
                        }
                    }
                    retVONode.setPrice(price);
                    retVONode.setCost(price * retVONode.getCount());
                    prePaid += retVONode.getCost();




                //List<ServiceOrdersitems> ordersitemsList = ordersitemsMapper.selectServiceOrdersitemsByOrderId(order.getOrderId());
                //for (ServiceOrdersitems ordersitems : ordersitemsList) {//项目、套餐、耗材包
                //    ItemComboReturn retNode = new ItemComboReturn();
                //    PatientOrderInfo retVONode = new PatientOrderInfo();
                //    List<ServiceItemscombo> itemscombos = itemscomboMapper.selectByItemId(ordersitems.getOrdersitemsItemid());
                //    ServiceItems item = itemsMapper.selectServiceItemsByItemId(ordersitems.getOrdersitemsItemid());
                //    retNode.setItem(item);
                //    retVONode.initItem(item);//项目信息录入
                //
                //    for (ServiceItemscombo itemscombo : itemscombos){
                //        Long price = 0L;
                //        ServiceOrderscombo searchOrdersCombo = new ServiceOrderscombo();
                //        searchOrdersCombo.setOrderscomboOrderid(ordersitems.getOrdersitemsOrderid());
                //        searchOrdersCombo.setOrderscomboComboid(itemscombo.getItemscomboSuppliesid());
                //        searchOrdersCombo.setOrderscomboDelFlag("0");
                //        List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboList(searchOrdersCombo);
                //        if (orderscomboList.size() > 0){
                //            ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemscombo.getItemscomboSuppliesid());
                //            retVONode.setSpecId(combo.getComboId());
                //            retVONode.setSpecName(combo.getComboName());
                //            retVONode.setCount(orderscomboList.get(0).getOrderscomboCount());
                //            price += combo.getComboPrice();
                //
                //            List<ServicePackagescombo> packagescombos = packagescomboMapper.selectServicePackagescomboByComboId(combo.getComboId());
                //            for (ServicePackagescombo packagescombo : packagescombos){
                //                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
                //                ServiceOrderspackages searchOrdersPackages = new ServiceOrderspackages();
                //                searchOrdersPackages.setOrderspackagesOrderid(ordersitems.getOrdersitemsOrderid());
                //                searchOrdersPackages.setOrderspackagesPackageid(packages.getPackagesId());
                //                searchOrdersPackages.setOrderspackagesDelFlag("0");
                //                List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(searchOrdersPackages);
                //                if (orderspackagesList.size() > 0){
                //                    retVONode.setPkgId(packages.getPackagesId());
                //                    retVONode.setPkgName(packages.getPackagesName());
                //                    price += packages.getPackagesPrice();
                //                    break;
                //                }
                //            }
                //
                //            retVONode.setPrice(price);
                //            retVONode.setCost(price * retVONode.getCount());
                //            prePaid += retVONode.getCost();
                //            break;
                //
                //        }
                //    }
                    if (retOrderVONode.getOrderInfo() == null){
                        retOrderVONode.setOrderInfo(new ArrayList<PatientOrderInfo>());
                    }
                    retOrderVONode.getOrderInfo().add(retVONode);

                    int buttonFlag = 0;
                    int addBTFlag = 0;
                    List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(order.getOrderId());
                    ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(order.getOrderId());
                    if (retOrderVONode.getButtons() == null){
                        retOrderVONode.setButtons(new ArrayList<PatientOrderButton>());
                    }
                    if (orders.getOrderFlag() == 0){
                        if(orders.getOrderPay() == null){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toPay")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toPay", "去支付"));
                                addBTFlag = 0;buttonFlag++;
                            }

                        }
                        if(orders.getOrderPay() != null && "1".equals(payInfo.getPayStatus())){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toPay")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toPay", "去支付"));
                                addBTFlag = 0;buttonFlag++;
                            }
                            retOrderVONode.setOrderCode("unpaid");
                            retOrderVONode.setOrderStatus("待付款");
                        }

                        if(orders.getOrderServiceflag() == 12 && orders.getOrderFlag() == 0){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toPayDiff")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toPayDiff", "支付差价"));
                                addBTFlag = 0;buttonFlag++;
                            }

                        }
                        //if(orders.getOrderServiceflag() >= 15){
                        //    retOrderVONode.getButtons().add(new PatientOrderButton("toOrder", "再次购买"));
                        //}
                        ServicePicture searchPicture = new ServicePicture();
                        searchPicture.setPictureOrderid(order.getOrderId());
                        searchPicture.setPictureType("0");
                        searchPicture.setPictureDelFlag("0");
                        List<ServicePicture> picturesImedical = pictureMapper.selectServicePictureList(searchPicture);
                        if (picturesImedical.size() < 1){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("uploadMedical")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("uploadMedical", "就医证明"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        searchPicture = new ServicePicture();
                        searchPicture.setPictureOrderid(order.getOrderId());
                        searchPicture.setPictureType("1");
                        searchPicture.setPictureDelFlag("0");
                        List<ServicePicture> picturesConsume = pictureMapper.selectServicePictureList(searchPicture);
                        if (picturesConsume.size() < 1){
                            for(ServiceOrderspackages orderspackages : orderspackagesList){
                                if (orderspackages.getOrderspackagesPackageid() == 0){
                                    for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                        if(button.getType().equals("uploadConsume")){
                                            addBTFlag = 1;
                                            break;
                                        }
                                    }
                                    if(addBTFlag == 0){
                                        retOrderVONode.getButtons().add(new PatientOrderButton("uploadConsume", "耗材证明"));
                                        addBTFlag = 0;buttonFlag++;
                                        break;
                                    }

                                }
                            }
                        }
                        if(buttonFlag < 2 && orders.getOrderServiceflag() >= 3 && orders.getOrderServiceflag() <= 17){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toContactHosp")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toContactHosp", "联系医院"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        if(buttonFlag < 2 && orders.getOrderServiceflag() >= 8 && orders.getOrderServiceflag() <= 17){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toContactNur")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toContactNur", "联系护士"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        if((orders.getOrderServiceflag() < 9 && orders.getOrderServiceflag() != 4 )&& orders.getOrderServiceflag() != 2){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toEdit")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toEdit", "修改订单"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        if((orders.getOrderServiceflag() < 9 && orders.getOrderServiceflag() != 4 )&& orders.getOrderServiceflag() != 2){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toCancel")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toCancel", "取消订单"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        if(buttonFlag < 3 && orders.getOrderServiceflag() >= 15 ){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toDelete")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toDelete", "删除订单"));
                                addBTFlag = 0;buttonFlag++;
                            }
                        }
                        if (buttonFlag < 4){
                            if(orders.getOrderAssessmentid() == null){
                                if(orders.getOrderServiceflag() >= 11){
                                    for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                        if(button.getType().equals("toRate")){
                                            addBTFlag = 1;
                                            break;
                                        }
                                    }
                                    if(addBTFlag == 0){
                                        retOrderVONode.getButtons().add(new PatientOrderButton("toRate", "去评价"));
                                        addBTFlag = 0;buttonFlag++;
                                    }
                                }
                            }else{
                                ServiceAssessment assessment = assessmentMapper.selectServiceAssessmentByAssessmentId(orders.getOrderAssessmentid());
                                if("1".equals(assessment.getAssessmentUserstatus()) && orders.getOrderServiceflag() >= 11){
                                    for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                        if(button.getType().equals("toRate")){
                                            addBTFlag = 1;
                                            break;
                                        }
                                    }
                                    if(addBTFlag == 0){
                                        retOrderVONode.getButtons().add(new PatientOrderButton("toRate", "去评价"));
                                        addBTFlag = 0;buttonFlag++;
                                    }
                                }
                            }
                        }
                    }

                    //if(retOrderVONode.getPrePaid() == null){
                    //    retOrderVONode.setPrePaid(prePaid + 100);//一百块往返路程费（押金）
                    //}
                    retOrderVONode.setPrePaid(prePaid + 10000);//一百块往返路程费（押金）

                    List<ServicePicture> medicals = pictureMapper.selectMedicalListByOrderId(order.getOrderId());
                    PatientProofsInfo proofsInfo = new PatientProofsInfo();
                    proofsInfo.setMedicalImages(new ArrayList<String>());
                    proofsInfo.setConsumeImages(new ArrayList<String>());
                    for (ServicePicture medical : medicals){
                        proofsInfo.getMedicalImages().add(medical.getPicturePic());
                    }
                    List<ServicePicture> consumes = pictureMapper.selectConsumeListByOrderId(order.getOrderId());
                    for (ServicePicture consume : consumes){
                        proofsInfo.getConsumeImages().add(consume.getPicturePic());
                    }
                    if (medicals.size() == 0) proofsInfo.setMedicalTips("请上传处方、病历等就医证明");
                    if (consumes.size() == 0) proofsInfo.setConsumeTips("请上传耗材证明");

                    for(ServiceOrderspackages orderspackages : orderspackagesList){
                        if (orderspackages.getOrderspackagesPackageid() == 0){
                            proofsInfo.setNeedUploadConsume(true);
                            break;
                        }
                    }
                    retOrderVONode.setProofsInfo(proofsInfo);

                    PatientDispatchInfo dispatchInfo = new PatientDispatchInfo();

                    List<ServiceOrdernurse> ordernurseList = ordernurseMapper.selectServiceOrdernurseListByOrderId(order.getOrderId());
                    List<PatientNurseInfo> nurseInfoList = new ArrayList<PatientNurseInfo>();
                    for (ServiceOrdernurse ordernurse : ordernurseList){
                        ServiceNurse nurse = nurseMapper.selectServiceNurseByNurseId(ordernurse.getOrdernurseNurseid());
                        if (nurse != null){
                            PatientNurseInfo nurseInfo = new PatientNurseInfo();

                            nurseInfo.setNurseId(nurse.getNurseId());
                            nurseInfo.setNurseName(nurse.getNurseName());
                            nurseInfo.setNurseTel(nurse.getNurseTelephonenumber());

                            nurseInfoList.add(nurseInfo);
                        }

                    }
                    dispatchInfo.setNurseInfo(nurseInfoList);

                    PatientHospInfo hospInfo = new PatientHospInfo();
                    dispatchInfo.setHospInfo(hospInfo);
                    retOrderVONode.setDispatchInfo(dispatchInfo);

                    if (order.getOrderPay() == null){
                        retOrderVONode.setPrePaid(0L);
                    }


                }
                retOrderListVO.add(retOrderVONode);
            }

            // 分页逻辑
            Pageable pageable = PageRequest.of(page, size);
            int start = (int) pageable.getOffset();
            int end = Math.min((start + pageable.getPageSize()), retOrderListVO.size());
            List<PatientOrderReturnVO> pagedItemsList = retOrderListVO.subList(start, end);

            return new PageImpl<>(pagedItemsList, pageable, retOrderListVO.size());

        }catch (Exception e){
            return null;
        }
    }

    //@Transactional  暂存
    //public List<PatientOrderReturn> getOrderList(String labelStatus, LoginPatient oldPatient)
    //{
    //    List<PatientOrderReturn> retOrderList = new ArrayList<PatientOrderReturn>();
    //    List<PatientOrderReturnVO> retOrderListVO = new ArrayList<PatientOrderReturnVO>();
    //    try {
    //        ServiceOrders searchOrder = new ServiceOrders();
    //        searchOrder.setOrderUserid(oldPatient.getUserId());
    //        searchOrder.setOrderDelFlag("0");
    //
    //        pictureMapper.selectServicePictureByPictureId(1L);
    //
    //        Long[] orderServiceFlags = null;
    //        if (labelStatus.equals("unpaid")){
    //            searchOrder.setOrderUseFlag("1");
    //            orderServiceFlags = new Long[]{1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L};
    //        } else if (labelStatus.equals("unserved")) {
    //            orderServiceFlags = new Long[]{5L,6L,7L,8L};
    //        } else if (labelStatus.equals("serving")) {
    //            orderServiceFlags = new Long[]{9L,10L};
    //        } else if (labelStatus.equals("unsettled")) {
    //            orderServiceFlags = new Long[]{11L,12L,13L};
    //        }else if (labelStatus.equals("settled")){
    //            orderServiceFlags = new Long[]{14L,15L,16L,17L};
    //        }else {
    //            orderServiceFlags = new Long[]{1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L};
    //        }
    //
    //        List<ServiceOrders> ordersList = ordersMapper.selectServiceOrdersListAllByStatus(searchOrder, orderServiceFlags);
    //        for (ServiceOrders order : ordersList) {
    //            List<ItemComboReturn> retItemComboPackage = new ArrayList<ItemComboReturn>();
    //            PatientOrderReturn retOrderNode = new PatientOrderReturn();
    //            PatientOrderReturnVO retOrderVONode = new PatientOrderReturnVO();
    //
    //            retOrderNode.setOrder(order);//订单信息
    //            retOrderVONode.init(order);
    //
    //            ServicePay payInfo = payMapper.selectServicePayByPayId(order.getOrderPay());
    //            if(payInfo != null) retOrderNode.setServicePay(payInfo);//支付信息
    //            if(payInfo != null) retOrderVONode.initPay(payInfo);
    //
    //            ServiceCode code = codeMapper.selectServiceCodeByOrderId(order.getOrderId());
    //            if(code != null) retOrderNode.setCode(code.getCodeCode());//验证码
    //            if(code != null) retOrderVONode.setVerifiCode(code.getCodeCode());
    //
    //            List<ServiceOrdersitems> ordersitemsList = ordersitemsMapper.selectServiceOrdersitemsByOrderId(order.getOrderId());
    //            for (ServiceOrdersitems ordersitems : ordersitemsList) {//项目套餐耗材包
    //                ItemComboReturn retNode = new ItemComboReturn();
    //                PatientOrderInfo retVONode = new PatientOrderInfo();
    //                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(ordersitems.getOrdersitemsItemid());
    //                ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
    //                retNode.setItem(item);
    //                retVONode.initItem(item);
    //
    //
    //                ServiceItemscombo searchItemsCombo = new ServiceItemscombo();
    //                searchItemsCombo.setItemscomboItemid(item.getItemId());
    //                List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectServiceItemscomboList(searchItemsCombo);
    //                ArrayList<ComboPackageReturn> retChlComboList = new ArrayList<>();
    //                for (ServiceItemscombo itemCombo : itemscomboList){
    //                    ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemCombo.getItemscomboSuppliesid());
    //
    //                    ServicePackagescombo searchPackagesCombo = new ServicePackagescombo();
    //                    searchPackagesCombo.setPackagescomboComboid(combo.getComboId());
    //                    List<ServicePackagescombo> packagescomboList = packagescomboMapper.selectServicePackagescomboList(searchPackagesCombo);
    //                    ComboPackageReturn newChlNode = new ComboPackageReturn();
    //                    ArrayList<ServicePackages> packagesList = new ArrayList<>();
    //                    for (ServicePackagescombo packagescombo : packagescomboList) {
    //                        ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
    //                        packagesList.add(packages);
    //                    }
    //                    newChlNode.setPackages(packagesList);
    //                    newChlNode.setCombo(combo);
    //                    retChlComboList.add(newChlNode);
    //                }
    //                retNode.setComboPackages(retChlComboList);
    //                retItemComboPackage.add(retNode);
    //            }
    //            retOrderNode.setItemComboReturns(retItemComboPackage);
    //            retOrderList.add(retOrderNode);
    //        }
    //        return retOrderList;
    //
    //    }catch (Exception e){
    //        return null;
    //    }
    //}

    @Transactional
    public PatientOrderDetailRet getOrderDetail(Long orderId,LoginPatient oldPatient)
    {
        List<PatientOrderReturn> retOrderList = new ArrayList<PatientOrderReturn>();
        List<PatientOrderDetailRet> retOrderDetailVO = new ArrayList<PatientOrderDetailRet>();
        try {
            ServiceOrders searchOrder = new ServiceOrders();
            searchOrder.setOrderId(orderId);
            searchOrder.setOrderUserid(oldPatient.getUserId());
            searchOrder.setOrderDelFlag("0");

            List<ServiceOrders> ordersList = ordersMapper.selectServiceOrdersList(searchOrder);
            if (ordersList.size() == 0){
                throw new Exception("未找到订单信息");
            }

            ServiceOrders order = ordersList.get(0);
            PatientOrderReturn retOrderNode = new PatientOrderReturn();
            PatientOrderDetailRet retOrderVONode = new PatientOrderDetailRet();
            Long prePaid = 0L;

            retOrderNode.setOrder(order);//订单信息
            retOrderVONode.init(order);

            //ServicePay payInfo = payMapper.selectServicePayByPayId(order.getOrderPay());
            //if(payInfo != null) retOrderNode.setServicePay(payInfo);//支付信息
            //
            //payroadMapper;

            //if(payInfo != null) retOrderVONode.initPay(payInfo);

            ServiceCode code = codeMapper.selectServiceCodeByOrderId(order.getOrderId());
            if(code != null) retOrderNode.setCode(code.getCodeCode());//验证码
            if(code != null) retOrderVONode.setVerifiCode(code.getCodeCode());
            //
            //List<ServiceOrdersitems> ordersitemsList = ordersitemsMapper.selectServiceOrdersitemsByOrderId(order.getOrderId());
            //for (ServiceOrdersitems ordersitems : ordersitemsList) {//项目、套餐、耗材包
            //    ItemComboReturn retNode = new ItemComboReturn();
            //    PatientOrderInfo retVONode = new PatientOrderInfo();
            //    List<ServiceItemscombo> itemscombos = itemscomboMapper.selectByItemId(ordersitems.getOrdersitemsItemid());
            //    ServiceItems item = itemsMapper.selectServiceItemsByItemId(ordersitems.getOrdersitemsItemid());
            //    retNode.setItem(item);
            //    retVONode.initItem(item);//项目信息录入
            //
            //    for (ServiceItemscombo itemscombo : itemscombos){
            //        Long price = 0L;
            //        ServiceOrderscombo searchOrdersCombo = new ServiceOrderscombo();
            //        searchOrdersCombo.setOrderscomboOrderid(ordersitems.getOrdersitemsOrderid());
            //        searchOrdersCombo.setOrderscomboComboid(itemscombo.getItemscomboSuppliesid());
            //        searchOrdersCombo.setOrderscomboDelFlag("0");
            //        List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboList(searchOrdersCombo);
            //        if (orderscomboList.size() > 0){
            //            ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemscombo.getItemscomboSuppliesid());
            //            retVONode.setSpecId(combo.getComboId());
            //            retVONode.setSpecName(combo.getComboName());
            //            retVONode.setSpecPrice(combo.getComboCurrentprice());
            //            retVONode.setCount(orderscomboList.get(0).getOrderscomboCount());
            //            price += combo.getComboPrice();
            //
            //            List<ServicePackagescombo> packagescombos = packagescomboMapper.selectServicePackagescomboByComboId(combo.getComboId());
            //            for (ServicePackagescombo packagescombo : packagescombos){
            //                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
            //                ServiceOrderspackages searchOrdersPackages = new ServiceOrderspackages();
            //                searchOrdersPackages.setOrderspackagesOrderid(ordersitems.getOrdersitemsOrderid());
            //                searchOrdersPackages.setOrderspackagesPackageid(packages.getPackagesId());
            //                searchOrdersPackages.setOrderspackagesDelFlag("0");
            //                List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(searchOrdersPackages);
            //                if (orderspackagesList.size() > 0){
            //                    retVONode.setPkgId(packages.getPackagesId());
            //                    retVONode.setPkgName(packages.getPackagesName());
            //                    retVONode.setPkgAmount(packages.getPackagesPrice());
            //                    price += packages.getPackagesPrice();
            //                    break;
            //                }
            //            }
            //
            //            retVONode.setPrice(price);
            //            retVONode.setCost(price * retVONode.getCount());
            //            prePaid += retVONode.getCost();
            //            break;
            //
            //        }
            //    }
            //


            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(order.getOrderId());
            for (ServiceOrderscombo orderscombo : orderscomboList) {
                PatientOrderInfo retVONode = new PatientOrderInfo();
                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(orderscombo.getOrderscomboComboid());
                ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
                ServiceCombo combo = comboMapper.selectServiceComboByComboIdNew(orderscombo.getOrderscomboComboid());
                retVONode.initItem(item);//项目信息录入
                Long price = 0L;
                retVONode.setSpecId(combo.getComboId());
                retVONode.setSpecName(combo.getComboName());
                retVONode.setSpecPrice(combo.getComboCurrentprice());
                retVONode.setCount(orderscomboList.get(0).getOrderscomboCount());
                price += combo.getComboPrice();

                List<ServicePackagescombo> packagescombos = packagescomboMapper.selectServicePackagescomboByComboId(combo.getComboId());
                for (ServicePackagescombo packagescombo : packagescombos) {
                    ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
                    ServiceOrderspackages searchOrdersPackages = new ServiceOrderspackages();
                    searchOrdersPackages.setOrderspackagesOrderid(order.getOrderId());
                    searchOrdersPackages.setOrderspackagesPackageid(packages.getPackagesId());
                    searchOrdersPackages.setOrderspackagesDelFlag("0");
                    List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(searchOrdersPackages);
                    if (orderspackagesList.size() > 0) {
                        retVONode.setPkgId(packages.getPackagesId());
                        retVONode.setPkgName(packages.getPackagesName());
                        retVONode.setPkgAmount(packages.getPackagesPrice());
                        price += packages.getPackagesPrice();
                        break;
                    }


                }

                retVONode.setPrice(price);
                retVONode.setCost(price * retVONode.getCount());
                prePaid += retVONode.getCost();
                retVONode.setFromNur(false);
                ServiceUsers users = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());
                if (!orderscombo.getOrderscomboCreateBy().equals(users.getUsersName())){
                    retVONode.setFromNur(true);
                }

                if (retOrderVONode.getOrderInfo() == null){
                    retOrderVONode.setOrderInfo(new ArrayList<PatientOrderInfo>());
                }
                retOrderVONode.getOrderInfo().add(retVONode);

                ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
                List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(order.getOrderId());
                if (retOrderVONode.getButtons() == null){
                    retOrderVONode.setButtons(new ArrayList<PatientOrderButton>());
                }
                int addBTFlag = 0;
                if (orders.getOrderFlag() == 0) {
                    if(orders.getOrderPay() == null){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toPay")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toPay", "去支付"));
                            addBTFlag = 0;
                        }
                    }
                    if(orders.getOrderPay() != null){
                        ServicePay payInfo = payMapper.selectServicePayByPayId(orders.getOrderPay());

                        if ("1".equals(payInfo.getPayStatus())){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toPay")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toPay", "去支付"));
                                addBTFlag = 0;
                            }
                            retOrderVONode.setOrderCode("unpaid");
                            retOrderVONode.setOrderStatus("待付款");
                            retOrderVONode.setOrderPayTip("请在 30分钟 内支付并完善信息，否则订单将会失效");
                            retOrderVONode.setOrderProcessTip("请尽快支付并完善信息，否则订单将会失效");
                        }
                    }

                    if(orders.getOrderServiceflag() == 12 && orders.getOrderFlag() == 0){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toPayDiff")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toPayDiff", "支付差价"));
                            addBTFlag = 0;
                        }
                    }

                    ServicePicture searchPicture = new ServicePicture();
                    searchPicture.setPictureOrderid(orderId);
                    searchPicture.setPictureType("0");
                    searchPicture.setPictureDelFlag("0");
                    List<ServicePicture> picturesImedical = pictureMapper.selectServicePictureList(searchPicture);
                    if (picturesImedical.size() <1){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("uploadMedical")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("uploadMedical", "就医证明"));
                            addBTFlag = 0;
                        }
                    }
                    searchPicture = new ServicePicture();
                    searchPicture.setPictureOrderid(orderId);
                    searchPicture.setPictureType("1");
                    searchPicture.setPictureDelFlag("0");
                    List<ServicePicture> picturesConsume = pictureMapper.selectServicePictureList(searchPicture);
                    if (picturesConsume.size() <1){
                        for(ServiceOrderspackages orderspackages : orderspackagesList){
                            if (orderspackages.getOrderspackagesPackageid() == 0){
                                for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                    if(button.getType().equals("uploadConsume")){
                                        addBTFlag = 1;
                                        break;
                                    }
                                }
                                if(addBTFlag == 0){
                                    retOrderVONode.getButtons().add(new PatientOrderButton("uploadConsume", "耗材证明"));
                                    addBTFlag = 0;
                                }
                                break;
                            }
                        }
                    }
                    if((orders.getOrderServiceflag() < 9 && orders.getOrderServiceflag() != 4 )&& orders.getOrderServiceflag() != 2){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toEdit")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toEdit", "修改订单"));
                            addBTFlag = 0;
                        }
                    }
                    if((orders.getOrderServiceflag() < 8 && orders.getOrderServiceflag() != 4 )&& orders.getOrderServiceflag() != 2){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toCancel")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toCancel", "取消订单"));
                            addBTFlag = 0;
                        }
                    }
                    if(orders.getOrderServiceflag() >= 15 ){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toDelete")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toDelete", "删除订单"));
                            addBTFlag = 0;
                        }
                    }
                    if(orders.getOrderAssessmentid() == null){
                        if(orders.getOrderServiceflag() >= 11){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toRate")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toRate", "去评价"));
                                addBTFlag = 0;
                            }
                        }
                    }else{
                        ServiceAssessment assessment = assessmentMapper.selectServiceAssessmentByAssessmentId(orders.getOrderAssessmentid());
                        if("1".equals(assessment.getAssessmentUserstatus()) && orders.getOrderServiceflag() >= 11){
                            for (PatientOrderButton button : retOrderVONode.getButtons()) {
                                if(button.getType().equals("toRate")){
                                    addBTFlag = 1;
                                    break;
                                }
                            }
                            if(addBTFlag == 0){
                                retOrderVONode.getButtons().add(new PatientOrderButton("toRate", "去评价"));
                                addBTFlag = 0;
                            }
                        }
                    }
                    //if(orders.getOrderServiceflag() >= 15){
                    //    retOrderVONode.getButtons().add(new PatientOrderButton("toOrder", "再次购买"));
                    //}
                    if(orders.getOrderServiceflag() >= 3 && orders.getOrderServiceflag() <= 17){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toContactHosp")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toContactHosp", "联系医院"));
                            addBTFlag = 0;
                        }
                    }
                    if(orders.getOrderServiceflag() >= 8 && orders.getOrderServiceflag() <= 17){
                        for (PatientOrderButton button : retOrderVONode.getButtons()) {
                            if(button.getType().equals("toContactNur")){
                                addBTFlag = 1;
                                break;
                            }
                        }
                        if(addBTFlag == 0){
                            retOrderVONode.getButtons().add(new PatientOrderButton("toContactNur", "联系护士"));
                            addBTFlag = 0;
                        }
                    }

                }


                //if(retOrderVONode.getPrePaid() == null){
                //    retOrderVONode.setPrePaid(prePaid + 100);//一百块往返路程费（押金）
                //}

                List<ServicePicture> medicals = pictureMapper.selectMedicalListByOrderId(order.getOrderId());
                PatientProofsInfo proofsInfo = new PatientProofsInfo();
                proofsInfo.setMedicalImages(new ArrayList<String>());
                proofsInfo.setConsumeImages(new ArrayList<String>());
                for (ServicePicture medical : medicals){
                    proofsInfo.getMedicalImages().add(medical.getPicturePic());
                }
                List<ServicePicture> consumes = pictureMapper.selectConsumeListByOrderId(order.getOrderId());
                for (ServicePicture consume : consumes){
                    proofsInfo.getConsumeImages().add(consume.getPicturePic());
                }
                if (medicals.size() == 0) proofsInfo.setMedicalTips("请上传处方、病历等就医证明");
                if (consumes.size() == 0) proofsInfo.setConsumeTips("请上传耗材证明");
                retOrderVONode.setProofsInfo(proofsInfo);
                for(ServiceOrderspackages orderspackages : orderspackagesList){
                    if (orderspackages.getOrderspackagesPackageid() == 0){
                        proofsInfo.setNeedUploadConsume(true);
                        break;
                    }
                }

                PatientDispatchInfo dispatchInfo = new PatientDispatchInfo();
                List<ServiceOrdernurse> ordernurseList = ordernurseMapper.selectServiceOrdernurseListByOrderId(order.getOrderId());
                List<PatientNurseInfo> nurseInfoList = new ArrayList<PatientNurseInfo>();
                for (ServiceOrdernurse ordernurse : ordernurseList){
                    ServiceNurse nurse = nurseMapper.selectServiceNurseByNurseId(ordernurse.getOrdernurseNurseid());
                    if (nurse != null){
                        PatientNurseInfo nurseInfo = new PatientNurseInfo();

                        nurseInfo.setNurseId(nurse.getNurseId());
                        nurseInfo.setNurseName(nurse.getNurseName());
                        nurseInfo.setNurseTel(nurse.getNurseTelephonenumber());

                        nurseInfoList.add(nurseInfo);
                    }

                }
                dispatchInfo.setNurseInfo(nurseInfoList);

                PatientHospInfo hospInfo = new PatientHospInfo();
                dispatchInfo.setHospInfo(hospInfo);
                retOrderVONode.setDispatchInfo(dispatchInfo);

                //被服务信息
                retOrderVONode.setServeInfo(getServeInfo(order.getOrderId(),oldPatient));
                retOrderVONode.setPaidInfo(getPaidInfo(order.getOrderId(),oldPatient));
                retOrderVONode.setCheckInfo(getCheckInfo(order.getOrderId(),oldPatient));

            }
            return retOrderVONode;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientCheckInfo getCheckInfo(Long orderId, LoginPatient oldPatient) {
        try {
            List<ServicePicture> pictures = pictureMapper.selectCheckListByOrderId(orderId);
            PatientCheckInfo checkInfo = new PatientCheckInfo();
            checkInfo.setCheckImages(new ArrayList<String>());
            for (ServicePicture picture : pictures){
                checkInfo.getCheckImages().add(picture.getPicturePic());
                checkInfo.setCheckTips(checkInfo.getCheckTips() + " ; " + picture.getPictureRemark());
            }

            return checkInfo;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientServeInfo getServeInfo(Long orderId, LoginPatient oldPatient) {
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);

            ServiceServed served = servedMapper.selectServiceServedByServedId(orders.getOrderServedid());
            ServiceAddress address = addressMapper.selectServiceAddressByAddressId(orders.getOrderAddressid());
            PatientServeInfo serveInfo = new PatientServeInfo();
            serveInfo.setServePersonId(served.getServedId());
            serveInfo.setServePerson(served.getServedName());
            serveInfo.setServeTel(served.getServedTelephonenumber());
            serveInfo.setServeAddress(address.getAddressInfo());

            DateFormat cstFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String serveTime = cstFormate.format(orders.getOrderScheduledtime());
            serveInfo.setServeTime(serveTime);

            return serveInfo;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientActual getActual(Long orderId,LoginPatient oldPatient) {
        try {
            PatientActual actual = new PatientActual();
            PatientServiceItems serviceItems = getServiceItems(orderId, oldPatient);
            PatientPackageItems packageItems = getPackageItems(orderId, oldPatient);
            PatientTaxiItems taxiItems = getTaxiItems(orderId, oldPatient);
            PatientOtherItems otherItems = getOtherItems(orderId, oldPatient);
            actual.setServiceItems(serviceItems);
            actual.setPackageItems(packageItems);
            actual.setTaxiItems(taxiItems);
            actual.setOtherItems(otherItems);

            actual.setTotalAmount(serviceItems.getAmount() + packageItems.getAmount() + taxiItems.getAmount() + otherItems.getAmount());

            return actual;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientServiceItems getServiceItems(Long orderId,LoginPatient oldPatient) {
        try {

            PatientServiceItems serviceItems = new PatientServiceItems();
            if (serviceItems.getItems() == null){
                serviceItems.setItems(new ArrayList<PatientServiceItemsItem>());
            }
            Long amount = 0L;
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
            for (ServiceOrderscombo orderscombo : orderscomboList){
                PatientServiceItemsItem itemNode = new PatientServiceItemsItem();
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                itemNode.setName(combo.getComboName());
                itemNode.setPrice(combo.getComboCurrentprice());
                itemNode.setCount(orderscombo.getOrderscomboCount());
                itemNode.setAmount(combo.getComboCurrentprice() * orderscombo.getOrderscomboCount());
                if (orderscombo.getOrderscomboCreateBy() != oldPatient.getUsername()){
                    itemNode.setFromNur(true);
                }
                amount = amount + itemNode.getAmount();
                serviceItems.getItems().add(itemNode);
            }
            serviceItems.setAmount(amount);
            return serviceItems;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientPackageItems getPackageItems(Long orderId,LoginPatient oldPatient) {
        try {

            PatientPackageItems packageItems = new PatientPackageItems();
            if (packageItems.getItems() == null){
                packageItems.setItems(new ArrayList<PatientPackageItemsItem>());
            }
            Long amount = 0L;
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(orderId);
            for (ServiceOrderspackages orderspackages : orderspackagesList){
                PatientPackageItemsItem itemNode = new PatientPackageItemsItem();
                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(orderspackages.getOrderspackagesPackageid());
                itemNode.setName(packages.getPackagesName());
                itemNode.setPrice(packages.getPackagesPrice());
                itemNode.setCount(orderspackages.getOrderspackagesCount());
                itemNode.setAmount(packages.getPackagesPrice() * orderspackages.getOrderspackagesCount());
                if (orderspackages.getOrderspackagesCreateBy() != oldPatient.getUsername()){
                    itemNode.setFromNur(true);
                }
                amount = amount + itemNode.getAmount();
                packageItems.getItems().add(itemNode);
            }
            packageItems.setAmount(amount);
            return packageItems;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientTaxiItems getTaxiItems(Long orderId,LoginPatient oldPatient) {
        try {

            PatientTaxiItems taxiItems = new PatientTaxiItems();
            if (taxiItems.getItems() == null){
                taxiItems.setItems(new ArrayList<PatientTaxiItemsItem>());
            }
            Long amount = 0L;
            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);
            PatientTaxiItemsItem itemNode = new PatientTaxiItemsItem();
            itemNode.setType("goto");
            itemNode.setAmount(payroad.getPayroadBill());
            amount = amount + payroad.getPayroadBill();
            taxiItems.getItems().add(itemNode);

            itemNode = new PatientTaxiItemsItem();
            itemNode.setType("back");
            itemNode.setAmount(payroad.getPayroadActualpay());
            amount = amount + payroad.getPayroadActualpay();
            taxiItems.getItems().add(itemNode);

            taxiItems.setAmount(amount);
            return taxiItems;
        }catch (Exception e){
            return null;
        }
    }


    @Transactional
    public PatientOtherItems getOtherItems(Long orderId,LoginPatient oldPatient) {
        try {

            PatientOtherItems otherItems = new PatientOtherItems();
            if (otherItems.getItems() == null){
                otherItems.setItems(new ArrayList<PatientOtherItemsItem>());
            }
            Long amount = 0L;
            List<ServiceOrderotherpay> orderotherpayList = orderotherpayMapper.selectOtherpayByOrderId(orderId);
            for (ServiceOrderotherpay orderotherpay : orderotherpayList){
                PatientOtherItemsItem itemNode = new PatientOtherItemsItem();
                itemNode.setName(orderotherpay.getOrderotherpayDesc());
                itemNode.setPrice(orderotherpay.getOrderotherpayPrice());
                itemNode.setCount(orderotherpay.getOrderotherpayCount());
                itemNode.setAmount(orderotherpay.getOrderotherpayPrice() * orderotherpay.getOrderotherpayCount());
                amount = amount + itemNode.getAmount();
                otherItems.getItems().add(itemNode);
            }
            otherItems.setAmount(amount);

            return otherItems;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PatientPrepaid getPrePaid(Long orderId,LoginPatient oldPatient) {
        try {

            PatientPrepaid prepaid = new PatientPrepaid();

            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServicePay pay = payMapper.selectServicePayByPayId(orders.getOrderPay());
            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);

            prepaid.setTotalAmount(pay.getPayAdvancepay() + payroad.getPayroadAdvancepay());
            prepaid.setSpecAmount(pay.getPayBill());
            prepaid.setPkgAmount(pay.getPayAdvancepay() - pay.getPayBill());
            prepaid.setTaxiAmount(payroad.getPayroadAdvancepay());

            return prepaid;

        }catch (Exception e){
            return null;
        }
    }





    @Transactional
    public PatientDifference getDifference(PatientActual actual, PatientPrepaid prepaid,LoginPatient oldPatient) {
        try {

            PatientDifference difference = new PatientDifference();
            Long amount = 0L;
            if (difference.getItems() == null){
                difference.setItems(new ArrayList<PatientDifferenceItem>());
            }
            PatientDifferenceItem differenceItem = new PatientDifferenceItem();
            differenceItem.setDesc("服务费差价");
            differenceItem.setType("service");
            differenceItem.setAmount(actual.getServiceItems().getAmount() - prepaid.getSpecAmount());
            amount += differenceItem.getAmount();
            difference.getItems().add(differenceItem);

            differenceItem = new PatientDifferenceItem();
            differenceItem.setDesc("耗材费差价");
            differenceItem.setType("package");
            differenceItem.setAmount(actual.getPackageItems().getAmount() - prepaid.getPkgAmount());
            amount += differenceItem.getAmount();
            difference.getItems().add(differenceItem);

            differenceItem = new PatientDifferenceItem();
            differenceItem.setDesc("行程费差价");
            differenceItem.setType("taxi");
            differenceItem.setAmount(actual.getTaxiItems().getAmount() - prepaid.getTaxiAmount());
            amount += differenceItem.getAmount();
            difference.getItems().add(differenceItem);

            differenceItem = new PatientDifferenceItem();
            differenceItem.setDesc("其他费用差价");
            differenceItem.setType("other");
            differenceItem.setAmount(actual.getOtherItems().getAmount());
            amount += differenceItem.getAmount();
            difference.getItems().add(differenceItem);

            difference.setAmount(amount);

            return difference;

        }catch (Exception e){
            return null;
        }
    }


    @Transactional
    public PatientPaidInfo getPaidInfo(Long orderId,LoginPatient oldPatient) {
        try {

            PatientPaidInfo paidInfo = new PatientPaidInfo();

            PatientPrepaid prePaid = getPrePaid(orderId, oldPatient);
            PatientActual actual = getActual(orderId, oldPatient);
            PatientDifference difference = getDifference(actual, prePaid, oldPatient);
            paidInfo.setActual(actual);
            paidInfo.setPrePaid(prePaid);
            paidInfo.setDifference(difference);

            paidInfo.setTotalAmount(prePaid.getTotalAmount());
            if (actual != null) paidInfo.setTotalAmount(actual.getTotalAmount());

            return paidInfo;

        }catch (Exception e){
            return null;
        }
    }







    @Transactional
    public List<PatientOrderReturn> getOrderDetialInPay(Long orderId,LoginPatient oldPatient)
    {
        try {
            List<PatientOrderReturn> retOrderList = new ArrayList<PatientOrderReturn>();
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);

            List<ItemComboReturn> retItemComboPackage = new ArrayList<ItemComboReturn>();
            PatientOrderReturn retOrderNode = new PatientOrderReturn();
            retOrderNode.setOrder(order);//订单信息
            ServicePay payInfo = payMapper.selectServicePayByPayId(order.getOrderPay());
            retOrderNode.setServicePay(payInfo);//支付信息
            ServiceCode code = codeMapper.selectServiceCodeByOrderId(order.getOrderId());
            retOrderNode.setCode(code.getCodeCode());//验证码

            List<ServiceOrdersitems> ordersitemsList = ordersitemsMapper.selectServiceOrdersitemsByOrderId(order.getOrderId());
            for (ServiceOrdersitems ordersitems : ordersitemsList) {//项目套餐耗材包
                ItemComboReturn retNode = new ItemComboReturn();
                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(ordersitems.getOrdersitemsItemid());
                ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
                retNode.setItem(item);
                ServiceItemscombo searchItemsCombo = new ServiceItemscombo();
                searchItemsCombo.setItemscomboItemid(item.getItemId());
                List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectServiceItemscomboList(searchItemsCombo);
                ArrayList<ComboPackageReturn> retChlComboList = new ArrayList<>();
                for (ServiceItemscombo itemCombo : itemscomboList){
                    ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemCombo.getItemscomboSuppliesid());

                    ServicePackagescombo searchPackagesCombo = new ServicePackagescombo();
                    searchPackagesCombo.setPackagescomboComboid(combo.getComboId());
                    List<ServicePackagescombo> packagescomboList = packagescomboMapper.selectServicePackagescomboList(searchPackagesCombo);
                    ComboPackageReturn newChlNode = new ComboPackageReturn();
                    ArrayList<ServicePackages> packagesList = new ArrayList<>();
                    for (ServicePackagescombo packagescombo : packagescomboList) {
                        ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagescombo.getPackagescomboPackagesid());
                        packagesList.add(packages);
                    }
                    newChlNode.setPackages(packagesList);
                    newChlNode.setCombo(combo);
                    retChlComboList.add(newChlNode);
                }
                retNode.setComboPackages(retChlComboList);
                retItemComboPackage.add(retNode);
            }
            retOrderNode.setItemComboReturns(retItemComboPackage);
            retOrderList.add(retOrderNode);

            return retOrderList;

        }catch (Exception e){
            return null;
        }
    }

    // 暂存 之后删除
    //@Transactional
    //public boolean newOrder(PatientOrderBody orderBody , LoginPatient oldPatient)
    //{
    //    try {
    //        ServiceOrders newOrder = new ServiceOrders();
    //        SnowFlake idWorker = new SnowFlake(0, 0);
    //        long id = idWorker.nextId();
    //        newOrder.setOrderUserid(oldPatient.getUserId());
    //        newOrder.setOrderCode(String.valueOf(id));
    //        newOrder.setOrderServedid(orderBody.getOrderServedid());
    //        newOrder.setOrderAddressid(orderBody.getOrderAddressid());
    //        newOrder.setOrderServiceflag(1);
    //        newOrder.setOrderCreatetime(new Date());
    //        newOrder.setOrderScheduledtime(orderBody.getOrderScheduledtime());
    //        newOrder.setOrderRemark(orderBody.getOrderRemark());
    //        newOrder.setOrderCreateBy(oldPatient.getUsername());
    //        newOrder.setOrderCreateTime(new Date());
    //        newOrder.setOrderUpdateBy(oldPatient.getUsername());
    //        newOrder.setOrderUpdateTime(new Date());
    //
    //        ordersMapper.insertServiceOrders(newOrder);
    //
    //        ServicePayroad newPayroad = new ServicePayroad();
    //        newPayroad.setPayroadOrderid(newOrder.getOrderId());
    //        newPayroad.setPayroadAdvancepay(orderBody.getPayRoad());
    //        newPayroad.setPayroadStatus("1");
    //        newPayroad.setPayroadStatusfinish("1");
    //        newPayroad.setPayroadCreateBy(oldPatient.getUsername());
    //        newPayroad.setPayroadCreateTime(new Date());
    //        newPayroad.setPayroadUpdateBy(oldPatient.getUsername());
    //        newPayroad.setPayroadUpdateTime(new Date());
    //
    //        payroadMapper.insertServicePayroad(newPayroad);
    //
    //        List<ServiceMycart> mycarts = mycartMapper.selectServiceMycartByMycartUserId(oldPatient.getUserId());
    //        for (ServiceMycart mycart : mycarts) {
    //            ServiceOrderscombo newOrdersCombo = new ServiceOrderscombo();
    //            newOrdersCombo.setOrderscomboComboid(mycart.getMycartItemid());
    //            newOrdersCombo.setOrderscomboCount(Long.valueOf(mycart.getMycartNum()));
    //            newOrdersCombo.setOrderscomboOrderid(newOrder.getOrderId());
    //            newOrdersCombo.setOrderscomboCreateBy(oldPatient.getUsername());
    //            newOrdersCombo.setOrderscomboCreateTime(new Date());
    //            newOrdersCombo.setOrderscomboUpdateBy(oldPatient.getUsername());
    //            newOrdersCombo.setOrderscomboUpdateTime(new Date());
    //            orderscomboMapper.insertServiceOrderscombo(newOrdersCombo);
    //
    //            ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(mycart.getMycartItemid());
    //            ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
    //            ServiceOrdersitems newOrdersItem = new ServiceOrdersitems();
    //            newOrdersItem.setOrdersitemsItemid(item.getItemId());
    //            newOrdersItem.setOrdersitemsCount(Long.valueOf(mycart.getMycartNum()));
    //            newOrdersItem.setOrdersitemsOrderid(newOrder.getOrderId());
    //            newOrdersItem.setOrdersitemsCreateBy(oldPatient.getUsername());
    //            newOrdersItem.setOrdersitemsCreateTime(new Date());
    //            newOrdersItem.setOrdersitemsUpdateBy(oldPatient.getUsername());
    //            newOrdersItem.setOrdersitemsUpdateTime(new Date());
    //            ordersitemsMapper.insertServiceOrdersitems(newOrdersItem);
    //
    //        }
    //    }catch (Exception e){
    //        return false;
    //    }
    //    return true;
    //}

    @Transactional
    public ServiceOrders newOrder(PatientOrderRequest orderBody , LoginPatient oldPatient)
    {
        try {
            Long newTotalAmount = 0L;
            ServiceOrders newOrder = new ServiceOrders();
            SnowFlake idWorker = new SnowFlake(0, 0);
            long id = idWorker.nextId();
            newOrder.setOrderUserid(oldPatient.getUserId());
            newOrder.setOrderCode(String.valueOf(id));
            newOrder.setOrderServedid(orderBody.getBookPersonId());
            ServiceServed served = servedMapper.selectServiceServedByServedId(orderBody.getBookPersonId());
            newOrder.setOrderAddressid(served.getServedAddress());//地址
            newOrder.setOrderServiceflag(1);
            newOrder.setOrderUseFlag("1");
            newOrder.setOrderCreatetime(new Date());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date scheduledtime = formatter.parse(orderBody.getBookDate());
            newOrder.setOrderScheduledtime(scheduledtime);
            //newOrder.setOrderRemark(orderBody.getOrderRemark());
            newOrder.setOrderCreateBy(oldPatient.getUsername());
            newOrder.setOrderCreateTime(new Date());
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());

            ordersMapper.insertServiceOrders(newOrder);

            ServicePayroad newPayroad = new ServicePayroad();
            newPayroad.setPayroadOrderid(newOrder.getOrderId());
            //newPayroad.setPayroadAdvancepay(orderBody.getPayRoad());
            newPayroad.setPayroadAdvancepay(Long.valueOf("10000"));
            newPayroad.setPayroadStatus("1");
            newPayroad.setPayroadStatusfinish("1");
            newPayroad.setPayroadCreateBy(oldPatient.getUsername());
            newPayroad.setPayroadCreateTime(new Date());
            newPayroad.setPayroadUpdateBy(oldPatient.getUsername());
            newPayroad.setPayroadUpdateTime(new Date());

            payroadMapper.insertServicePayroad(newPayroad);

            for (PatientOrderRequestNode order : orderBody.getOrders()) {
                Long tempCount = 0L;
                Long count = order.getSelectedCount();
                Long comboId = order.getSelectedSpecId();
                if (comboId == 0L){
                    count = 1L;
                }
                ServiceOrderscombo newOrdersCombo = new ServiceOrderscombo();
                newOrdersCombo.setOrderscomboComboid(comboId);
                newOrdersCombo.setOrderscomboCount(count);
                newOrdersCombo.setOrderscomboOrderid(newOrder.getOrderId());
                newOrdersCombo.setOrderscomboCreateBy(oldPatient.getUsername());
                newOrdersCombo.setOrderscomboCreateTime(new Date());
                newOrdersCombo.setOrderscomboUpdateBy(oldPatient.getUsername());
                newOrdersCombo.setOrderscomboUpdateTime(new Date());
                orderscomboMapper.insertServiceOrderscombo(newOrdersCombo);
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(comboId);
                if( combo == null ){
                    throw new Exception("套餐不存在");
                }
                tempCount = tempCount + combo.getComboCurrentprice();

                Long itemId = order.getSelectedItemId();
                ServiceOrdersitems newOrdersItem = new ServiceOrdersitems();
                newOrdersItem.setOrdersitemsItemid(itemId);
                newOrdersItem.setOrdersitemsCount(count);
                newOrdersItem.setOrdersitemsOrderid(newOrder.getOrderId());
                newOrdersItem.setOrdersitemsCreateBy(oldPatient.getUsername());
                newOrdersItem.setOrdersitemsCreateTime(new Date());
                newOrdersItem.setOrdersitemsUpdateBy(oldPatient.getUsername());
                newOrdersItem.setOrdersitemsUpdateTime(new Date());
                ordersitemsMapper.insertServiceOrdersitems(newOrdersItem);

                Long packagesId = order.getSelectedPkgId();
                if (packagesId != null) {
                    ServiceOrderspackages newOrdersPackages = new ServiceOrderspackages();
                    newOrdersPackages.setOrderspackagesPackageid(packagesId);
                    newOrdersPackages.setOrderspackagesCount(count);
                    newOrdersPackages.setOrderspackagesOrderid(newOrder.getOrderId());
                    newOrdersPackages.setOrderspackagesCreateBy(oldPatient.getUsername());
                    newOrdersPackages.setOrderspackagesCreateTime(new Date());
                    newOrdersPackages.setOrderspackagesUpdateBy(oldPatient.getUsername());
                    newOrdersPackages.setOrderspackagesUpdateTime(new Date());
                    orderspackagesMapper.insertServiceOrderspackages(newOrdersPackages);
                    ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(packagesId);
                    if( packages == null ){
                        throw new Exception("耗材包不存在");
                    }
                    tempCount = tempCount + packages.getPackagesPrice();
                }

                tempCount = tempCount * count;

                if(order.getSelectedAmount() != tempCount){
                    order.setSelectedAmount(tempCount);
                }
                newTotalAmount += order.getSelectedAmount();
            }
            if(orderBody.getTotalAmount() != newTotalAmount) {
                orderBody.setTotalAmount(newTotalAmount);//费用核对,没啥用处
            }
            addOrderProcess(newOrder.getOrderId());

            return newOrder;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public boolean cancelOrder(Long orderId , LoginPatient oldPatient)
    {
        try {
            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderId);
            newOrder.setOrderFlag(1);
            newOrder.setOrderServiceflag(2);
            newOrder.setOrderUseFlag("2");
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());
            ordersMapper.updateServiceOrders(newOrder);
            addOrderProcess(newOrder.getOrderId());

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public WxPayRespVO payOrder(Long orderId , LoginPatient oldPatient, HttpServletRequest req)
    {
        try {
            ServicePay newPay = new ServicePay();
            //支付接口
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(oldPatient.getUserId());

            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);
            Long comboAmount = 0L;
            Long packageAmount = 0L;
            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
            for (ServiceOrderscombo orderscombo : orderscomboList){
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                comboAmount += orderscombo.getOrderscomboCount() * combo.getComboCurrentprice();
            }
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(orderId);
            for (ServiceOrderspackages orderspackages : orderspackagesList){
                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(orderspackages.getOrderspackagesPackageid());
                packageAmount += orderspackages.getOrderspackagesCount() * packages.getPackagesPrice();
            }

            newPay.setPayAdvancepay(comboAmount + packageAmount);
            newPay.setPayBill(comboAmount);

            //String token_url = "https://hlwyy.ldqyylzx.cn/dhccam/token/generate?grant_type=api_credentials";
            //
            //HttpHeaders headers = new HttpHeaders();
            //headers.set("Authorization", base64("a785cf74-de42-6905-2b2f-15ec02d376e9:34fb7fa64f43031419434c211ac48217"));
            //
            //Map<String, String> paramMap = new HashMap<>();
            //HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
            //System.out.println(httpEntity);
            //ResponseEntity<Object> response = restTemplate.postForEntity(token_url, httpEntity, Object.class);
            //Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
            //String token = (String) responseBody.get("access_token");
            //
            ////System.out.println(token);
            ////
            ////JSONObject tradeJson = createTradeJson(orderId, newPay.getPayAdvancepay(), oldPatient);
            ////
            ////System.out.println("tradeJson:");
            ////System.out.println(tradeJson);
            ////
            ////String payJson = tradeJson.toString();
            ////
            ////System.out.println(payJson);
            ////String ss = JSONUtils.toJSONString(payJson).replace("/", "\\/");
            ////System.out.println(ss);
            //////String bizContent = AESUtils.Encrypt(ss);
            ////String bizContent = AESUtils.Encrypt(payJson);
            ////
            ////System.out.println(bizContent);
            ////
            ////String unifiedSign = createUnifiedSign(tradeJson, token).toUpperCase();
            ////
            ////System.out.println(unifiedSign.toUpperCase());
            ////
            ////JSONObject unifiedOrderJson = createUnifiedOrderJson(bizContent, token, unifiedSign);
            ////
            ////System.out.println(unifiedOrderJson);
            //
            //String unifiedorder_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
            //
            ////headers = new HttpHeaders();
            ////headers.set("Content-Type", "application/json");
            //
            ////Map<String, Object> unifiedMap = unifiedOrderJson.toMap();
            ////HttpEntity<Map<String, Object>> unifiedEntity = new HttpEntity<>(unifiedMap, headers);
            ////System.out.println(unifiedEntity);
            //
            //
            //
            ////String s = HttpUtils.sendPost(unifiedorder_url, unifiedOrderJson.toString());
            //Map<String, Object> data = new HashMap<String, Object>();
            ////Map<String, Object> header = new HashMap<String, Object>();
            ////header.put("Content-Type", "application/json");
            ////Map<String, Object> body = new HashMap<String, Object>();
            //data.put("tradeDesc", "HLHSSMPrePay");
            //data.put("orgId", "620000001222");
            //data.put("tradeOrgCode", "JKL");
            //data.put("shouldPay", ((float)(newPay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) / 100) + "");
            //data.put("total", ((float)(newPay.getPayAdvancepay()+ payroad.getPayroadAdvancepay()) / 100) + "");
            //data.put("coupon", "0");
            //data.put("orgOrderNo", orderId);
            ////data.put("notifyUrl", "http://192.168.2.17/prod-api/appPatient/appPatientOrder/notifyPay");
            ////data.put("openid", oldPatient.getUser().getUsersOpenid());
            //data.put("openid", users.getUsersOpenid());
            //
            //data.put("orderType", "Other");
            //data.put("useType", "wechatminipay");
            //data.put("timestamp", Instant.now().getEpochSecond());
            //String sign = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", data);
            //data.put("sign", sign);
            ////data.put("headers", header);
            ////data.put("body", body);
            //
            //Map<String, Object> stringObjectMap = buildMapHl( data, "paycenter.paygateway.unifiedorder", "body", token);
            ////unifiedEntity = new HttpEntity<>(stringObjectMap, headers);
            //
            //headers = new HttpHeaders();
            //headers.set("content-type", "application/json");
            //
            //HttpEntity<Map<String, Object>> httpEntityNew = new HttpEntity<>(stringObjectMap, headers);
            //System.out.println(httpEntityNew);
            //
            //ResponseEntity<Object> orderPayInfo = restTemplate.postForEntity(unifiedorder_url, httpEntityNew, Object.class);
            //Map<String, Object> orderPayInfoBody = (Map<String, Object>) orderPayInfo.getBody();
            //String payCodeOld = (String) orderPayInfoBody.get("data");
            //String payCode = AESUtils.Decrypt(payCodeOld);
            //JSONObject jsonObject = new JSONObject(payCode);
            //payCode = jsonObject.getString("orderNo");
            ////ResponseEntity<Object> objectResponseEntity = restTemplate.postForEntity(unifiedorder_url, unifiedEntity, Object.class);
            //
            //String gateway_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
            //Map<String, Object> dataPay = new HashMap<String, Object>();
            //dataPay.put("tradeDesc", "HLHSSMPrePay");
            //dataPay.put("orgId", "620000001222");
            //dataPay.put("tradeOrgCode", "JKL");
            //dataPay.put("shouldPay", ((float)(newPay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) / 100) + "");
            //dataPay.put("total", ((float)(newPay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) / 100) + "");
            //dataPay.put("coupon", "0");
            //dataPay.put("orgOrderNo", orderId);
            //dataPay.put("openid", users.getUsersOpenid());
            //
            //dataPay.put("orderType", "Other");
            //dataPay.put("regNo", users.getUsersId());
            //dataPay.put("orderNo", payCode);
            //dataPay.put("sourceCode", "7");
            //dataPay.put("type", "Other");
            //dataPay.put("useType", "wechatminipay");
            //dataPay.put("timeStamp", Instant.now().getEpochSecond());
            //String signPay = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", dataPay);
            //dataPay.put("sign", signPay);
            //
            //
            //Map<String, Object> payObjectMap = buildMapHl( dataPay, "paycenter.paygateway.gateway", "body", token);
            ////unifiedEntity = new HttpEntity<>(stringObjectMap, headers);
            //
            //headers = new HttpHeaders();
            //headers.set("content-type", "application/json");
            //
            //HttpEntity<Map<String, Object>> httpEntityPay = new HttpEntity<>(payObjectMap, headers);
            //System.out.println(httpEntityPay);
            //
            //ResponseEntity<Object> appPayInfo = restTemplate.postForEntity(gateway_url, httpEntityPay, Object.class);
            //Map<String, Object> appPayInfoBody = (Map<String, Object>) appPayInfo.getBody();
            //String payDataOld = (String) appPayInfoBody.get("data");
            //String payData = AESUtils.Decrypt(payDataOld);

            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);

            // 使用自动更新平台证书的RSA配置
            // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
            Config config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId(wxPayV3Bean.getMchId())
                            // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                            .privateKeyFromPath(wxPayV3Bean.getKeyPath())
                            .merchantSerialNumber(wxPayV3Bean.getMchSerialNo())
                            .apiV3Key(wxPayV3Bean.getApiKeyV3())
                            .build();
            // 构建service
            JsapiService service = new JsapiService.Builder().config(config).build();
            // request.setXxx(val)设置所需参数，具体参数可见Request定义
            PrepayRequest request = new PrepayRequest();
            Amount amount = new Amount();
            amount.setTotal((int)((newPay.getPayAdvancepay() + payroad.getPayroadAdvancepay())));
            request.setAmount(amount);
            request.setAppid(wxPayV3Bean.getAppId());
            request.setMchid(wxPayV3Bean.getMchId());
            request.setDescription("prePay");
            //request.setNotifyUrl(wxPayV3Bean.getNotifyUrl());
            request.setNotifyUrl("http://47.104.182.208/prod-api/appPatient/appPatientOrder/notifyPay");
            request.setOutTradeNo(orders.getOrderCode());
            request.setAttach("prePay");
            Payer payer = new Payer();
            payer.setOpenid(oldPatient.getUser().getUsersOpenid());
            request.setPayer(payer);
            // 调用下单方法，得到应答
            // 调用微信sdk接口,生成预支付交易单
            PrepayResponse response = service.prepay(request);
            WxPayRespVO vo = new WxPayRespVO();
            Long timeStamp = System.currentTimeMillis() / 1000;
            vo.setTimeStamp(timeStamp);
            String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
            vo.setNonceStr(substring);
            String signatureStr = Stream.of(wxPayV3Bean.getAppId(), String.valueOf(timeStamp), substring, "prepay_id=" + response.getPrepayId())
                    .collect(Collectors.joining("\n", "", "\n"));
            String sign = WXPayUtil.getSign(signatureStr, wxPayV3Bean.getKeyPath());
            vo.setPaySign(sign);
            //vo.setSignType("RSA");
            vo.setPrepayId("prepay_id=" + response.getPrepayId());

            //JSONObject appPayObject = new JSONObject(payData);

            //ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);

            //newPay.setPayAdvancepaycode(payCode);
            //newPay.setPayAdvancepaytype("wxPay");
            //newPay.setPayStatus("1");
            //newPay.setPayStatusfinish("1");
            //newPay.setPayCreateBy(oldPatient.getUsername());
            //newPay.setPayCreateTime(new Date());
            //newPay.setPayUpdateBy(oldPatient.getUsername());
            //newPay.setPayUpdateTime(new Date());
            //if (orders.getOrderPay() != null){
            //    newPay.setPayId(orders.getOrderPay());
            //    payMapper.updateServicePay(newPay);
            //}else{
            //    payMapper.insertServicePay(newPay);
            //}
            //
            //orders.setOrderPay(newPay.getPayId());
            //orders.setOrderUpdateBy(oldPatient.getUsername());
            //orders.setOrderUpdateTime(new Date());
            //ordersMapper.updateServiceOrders(orders);

            return vo;
        }catch (Exception e){
            return null;
        }
    }

    //public static Map<String, Object> postPlatformHl(Map<String, Object> params, String method) throws Exception {
    //    Map<String, Object> result = new HashMap<String, Object>();
    //    result = postBizRequest(buildMapHl(params, method, "body"));
    //    if ("200".equals(result.get("code"))) {
    //        if (!StringUtils.isEmpty(result.get("data"))) {
    //            result = treatResultData(result);
    //        }
    //    }
    //
    //    return result;
    //}

    public static Map<String, Object> buildMapHl(Object data, String method, String key, String token) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> bizContent = new HashMap<String, Object>();

        bizContent.put(key, data);
        map.put("token_type", "api_credentials");
        map.put("version", "v1.0");
        map.put("nonce_str", new Random().nextInt(10000));
        map.put("biz_content", bizContent);
        map.put("method", method);
        map.put("app_id", "a785cf74-de42-6905-2b2f-15ec02d376e9");

        //String token = getToken(ConstantUtil.GET_TOKEN_URL,"a785cf74-de42-6905-2b2f-15ec02d376e9", "34fb7fa64f43031419434c211ac48217");
        map.put("token", token);

        // 没有配置加密，不需要计算
        // 没有配置sign，不需要计算
        SignGenerator.buildSign(map, "prod_doc_sign_16", "MD5");
        String ss = JSONUtils.toJSONString(bizContent).replace("/", "\\/");
        map.put("biz_content", AESUtils.Encrypt(ss));
        return map;
    }

    public static void  buildSign(Map<String, Object> map, String security, String encodeType) {
        Map<String, Object> signMap = new HashMap<String, Object>();
        signMap.putAll(map);
        HashMap<String, Object> biz = (HashMap<String, Object>) signMap.get("biz_content");
        for (String key :biz.keySet()) {
            String value = null;
            if (biz.get(key) instanceof String) {
                value = (String) biz.get(key);
            } else {
                value = JSONUtils.toJSONString(biz.get(key));
            }
            signMap.put(key, value);
        }
        signMap.remove("biz_content");
        if ("MD5".equals(encodeType)) {
            List<Map.Entry<String, Object>> params = sortMap(signMap);
            StringBuilder sign = new StringBuilder();
            for (int i = 0; i < params.size(); i++) {
                if (!StringUtils.isEmpty(sign.toString())) {
                    sign.append("&");
                }
                sign.append(params.get(i).getKey()).append("=").append(params.get(i).getValue());
            }

            sign.append(security);
            //System.out.println("sign=====" + sign.toString());

            String md5Str = MD5Util.md5(sign.toString()).toUpperCase();;
            map.put("sign", md5Str);
        }

    }

    //public String createUnifiedOrderJson(Long orderId, String token, Long comboAmount, LoginPatient oldPatient) {
    //    JSONObject tradeJson = createTradeJson(orderId, comboAmount, oldPatient);
    //    JSONObject unifiedOrderJson = createUnifiedOrderJson(tradeJson.toString(), token);
    //    return unifiedOrderJson.toString();
    //}

    private JSONObject createTradeJson(Long orderId, Long comboAmount, LoginPatient oldPatient) {
        JSONObject tradeJson = new JSONObject();
        JSONObject body = new JSONObject();
        body.put("tradeDesc", "护理护士上门下单");
        body.put("orgId", "620000001222");
        body.put("tradeOrgCode", "JKL");
        body.put("shouldPay", comboAmount);
        body.put("total", comboAmount);
        body.put("coupon", "0");
        body.put("orgOrderNo", orderId);
        body.put("openid", oldPatient.getUser().getUsersOpenid());
        body.put("orderType", "Other");
        body.put("useType", "wechatminipay");
        body.put("timestamp", new Date().getTime());
        body.put("sign", "6b5b5539567a10a79f611eb4e61a19c1");

        JSONObject headers = new JSONObject();
        headers.put("Content-Type", "application/json");

        //String sign = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", body.toString());
        //body.put("sign", sign);
        tradeJson.put("body", body);
        tradeJson.put("headers", headers);

        return tradeJson;
    }

    private String createPaySign(Map<String, Object> data) {
        String signStr = "";
        signStr += "coupon" + "=" + data.get("coupon") + "&";
        signStr += "openid" + "=" + data.get("openid") + "&";
        signStr += "orderType" + "=" + data.get("orderType") + "&";
        signStr += "orgId" + "=" + data.get("orgId") + "&";
        signStr += "orgOrderNo" + "=" + data.get("orgOrderNo") + "&";
        signStr += "shouldPay" + "=" + data.get("shouldPay") + "&";
        signStr += "timestamp" + "=" + data.get("timestamp") + "&";
        signStr += "total" + "=" + data.get("total") + "&";
        signStr += "tradeDesc" + "=" + data.get("tradeDesc") + "&";
        signStr += "tradeOrgCode" + "=" + data.get("tradeOrgCode") + "&";
        signStr += "useType" + "=" + data.get("useType");
        signStr += "cspAVFPPuv2eWpShAekNnaCJXXrU5R28";

        String sign = MD5Util.md5(signStr);

        return sign;
    }

    private JSONObject createUnifiedOrderJson(String tradeJson, String token, String unifiedOrderSign) {
        JSONObject unifiedOrderJson = new JSONObject();
        unifiedOrderJson.put("app_id", "a785cf74-de42-6905-2b2f-15ec02d376e9");
        unifiedOrderJson.put("biz_content", tradeJson);
        unifiedOrderJson.put("method", "paycenter.paygateway.unifiedorder");
        SecureRandom secureRandom = new SecureRandom();
        unifiedOrderJson.put("nonce_str", (10000 + secureRandom.nextInt(90000)) + "");
        unifiedOrderJson.put("sign", unifiedOrderSign);
        unifiedOrderJson.put("token", token);
        unifiedOrderJson.put("token_type", "api_credentials");
        unifiedOrderJson.put("version", "v1.0");

        return unifiedOrderJson;
    }

    private String createUnifiedSign(JSONObject tradeJson, String token) {
        SecureRandom secureRandom = new SecureRandom();
        String signStr = "";
        signStr += "app_id=a785cf74-de42-6905-2b2f-15ec02d376e9&";
        signStr += "body=" + tradeJson.get("body").toString().replace("/", "\\/") + "&";
        signStr += "headers=" + tradeJson.get("headers").toString().replace("/", "\\/") + "&";
        //signStr += "&biz_content=" + tradeJson.toString() + "&";
        signStr += "method=paycenter.paygateway.unifiedorder&";
        signStr += "nonce_str=" + (10000 + secureRandom.nextInt(90000)) + "&";
        signStr += "token=" + token + "&";
        signStr += "token_type=api_credentials&";
        signStr += "version=v1.0";
        signStr += "prod_doc_sign_16";

        //JSONObject unifiedOrderJson = new JSONObject();
        //unifiedOrderJson.put("app_id", "a785cf74-de42-6905-2b2f-15ec02d376e9");
        ////unifiedOrderJson.put("biz_content", tradeJson.toString());
        //unifiedOrderJson.put("method", "paycenter.paygateway.unifiedorder");
        //
        //unifiedOrderJson.put("nonce_str", 10000 + secureRandom.nextInt(90000));
        //unifiedOrderJson.put("token", token);
        //unifiedOrderJson.put("token_type", "api_credentials");
        //unifiedOrderJson.put("version", "v1.0");

        //String unifiedOrderSign = phpSecret.phpSign("prod_doc_sign_16", unifiedOrderJson.toString());
        //String unifiedOrderSign = phpSecret.phpSign("prod_doc_sign_16", signStr);
        String unifiedOrderSign = MD5Util.md5(signStr).toUpperCase();
        //unifiedOrderJson.put("sign", unifiedOrderSign);

        return unifiedOrderSign;
    }


    //public void processOrder(String orderId, String comboAmount, LoginPatient oldPatient) {
    //    String token_url = "https://hlwyy.ldqyylzx.cn/dhccam/token/generate?grant_type=api_credentials";
    //
    //    HttpHeaders headers = new HttpHeaders();
    //    headers.set("Authorization", base64("a785cf74-de42-6905-2b2f-15ec02d376e9:34fb7fa64f43031419434c211ac48217"));
    //
    //    Map<String, String> paramMap = new HashMap<>();
    //    HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
    //    ResponseEntity<Object> response = restTemplate.postForEntity(token_url, httpEntity, Object.class);
    //    String oldBody = String.valueOf(response.getBody());
    //    JSONObject jsonObject = new JSONObject(oldBody);
    //    String token = (String) jsonObject.get("access_token");
    //
    //    String unifiedorderJson = createUnifiedOrderJson(orderId, token, comboAmount, oldPatient);
    //
    //    String unifiedorder_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
    //    Map<String, String> unifiedorderMap = new HashMap<>();
    //    unifiedorderMap.put("app_id", "a785cf74-de42-6905-2b2f-15ec02d376e9");
    //    unifiedorderMap.put("token", token);
    //    unifiedorderMap.put("method", "order.pay");
    //
    //    // 其他逻辑...
    //}

    private String base64(String input) {
        // 实现base64编码逻辑
        return Base64Util.base64(input);
    }


    @Transactional
    public boolean notifyPay(Long orderId, String transactionId)
    {
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServicePay newPay = payMapper.selectServicePayByPayId(orders.getOrderPay());
            ServiceUsers oldPatient = usersMapper.selectServiceUsersByUsersId(orders.getOrderUserid());
            //支付接口

            newPay.setPayAdvancepaytype(transactionId);
            newPay.setPayStatus("0");
            newPay.setPayStatusfinish("1");
            newPay.setPayUpdateBy(oldPatient.getUsersName());
            newPay.setPayUpdateTime(new Date());
            payMapper.updateServicePay(newPay);
            addPayProcess(orderId, oldPatient.getUsersId());
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(orderId);
            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);

            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderId);
            newOrder.setOrderPay(newPay.getPayId());
            newOrder.setOrderUpdateBy(oldPatient.getUsersName());
            newOrder.setOrderUpdateTime(new Date());

            List<ServicePicture> consumes = pictureMapper.selectConsumeListByOrderId(orderId);
            List<ServicePicture> medicals = pictureMapper.selectMedicalListByOrderId(orderId);

            if (medicals.size() > 0) {
                if(consumes.size() > 0){
                    newOrder.setOrderServiceflag(5);
                    newOrder.setOrderUseFlag("0");
                }else{
                    newOrder.setOrderServiceflag(5);
                    newOrder.setOrderUseFlag("0");
                    for (ServiceOrderspackages orderspackages : orderspackagesList) {
                        if(orderspackages.getOrderspackagesPackageid() == 0){
                            newOrder.setOrderServiceflag(3);
                            newOrder.setOrderUseFlag("1");
                            break;
                        }
                    }
                }
            }else{
                newOrder.setOrderServiceflag(3);
                newOrder.setOrderUseFlag("1");
            }
            ordersMapper.updateServiceOrders(newOrder);

            if (newOrder.getOrderServiceflag() == 5){
                addOrderProcess(newOrder.getOrderId());
            }

            Random randObj = new Random();
            String code = Integer.toString(1000 + randObj.nextInt(9000));
            ServiceCode newCode = new ServiceCode();
            newCode.setCodeCode(code);
            newCode.setCodeOrderid(orderId);
            newCode.setCodeUserid(oldPatient.getUsersId());
            newCode.setCodeUseflag("0");
            codeMapper.insertServiceCode(newCode);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean refundOrder(Long orderId ,Double refundBit, LoginPatient oldPatient)
    {
        try {
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(order.getOrderId());
            newOrder.setOrderServiceflag(4);
            newOrder.setOrderFlag(2);
            //退款接口
            newOrder.setOrderFlag(3);
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());
            if (order.getOrderPay() == null){
                ordersMapper.updateServiceOrders(newOrder);
                addOrderProcess(orderId);
                return true;
            }
            ServicePay pay = payMapper.selectServicePayByPayId(order.getOrderPay());

            if (pay.getPayAdvancepaytype() == null || "wxPay".equals(pay.getPayAdvancepaytype())) {
                ordersMapper.updateServiceOrders(newOrder);
                addOrderProcess(orderId);
                return true;
            }

            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());


            String token_url = "https://hlwyy.ldqyylzx.cn/dhccam/token/generate?grant_type=api_credentials";

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", base64("a785cf74-de42-6905-2b2f-15ec02d376e9:34fb7fa64f43031419434c211ac48217"));

            Map<String, String> paramMap = new HashMap<>();
            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
            System.out.println(httpEntity);
            ResponseEntity<Object> response = restTemplate.postForEntity(token_url, httpEntity, Object.class);
            Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
            String token = (String) responseBody.get("access_token");

            String gateway_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
            Map<String, Object> dataPay = new HashMap<String, Object>();
            dataPay.put("transactionId", pay.getPayAdvancepaytype());
            //dataPay.put("orgRefundOrder", pay.getPayAdvancepaycode());
            dataPay.put("totalFee", ((float)(pay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) / 100) + "");
            dataPay.put("refundFee", ((float)(pay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) / 100 * refundBit) + "");
            dataPay.put("memo", "allRefund");
            //dataPay.put("patientId", users.getUsersId());
            //dataPay.put("uid", users.getUsersOpenid());
            dataPay.put("timestamp", Instant.now().getEpochSecond());//todo 可能是大写
            String signPay = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", dataPay);
            dataPay.put("sign", signPay);

            Map<String, Object> payObjectMap = buildMapHl( dataPay, "paycenter.paygateway.refund", "body", token);
            //unifiedEntity = new HttpEntity<>(stringObjectMap, headers);

            headers = new HttpHeaders();
            headers.set("content-type", "application/json");

            HttpEntity<Map<String, Object>> httpEntityPay = new HttpEntity<>(payObjectMap, headers);
            System.out.println(httpEntityPay);
            ResponseEntity<Object> refundPayInfo = restTemplate.postForEntity(gateway_url, httpEntityPay, Object.class);

            Map<String, Object> refundPayInfoBody = (Map<String, Object>) refundPayInfo.getBody();
            String refundDataOld = (String) refundPayInfoBody.get("data");
            String refundData = AESUtils.Decrypt(refundDataOld);
            JSONObject refundObject = new JSONObject(refundData);
            Integer code = refundObject.getInt("code");
            String refundOrderNo = refundObject.getString("refundOrderNo");
            String refundId = refundObject.getString("refundId");

            if (code == 0){
                ServicePay newPay = new ServicePay();
                newPay.setPayId(order.getOrderPay());
                newPay.setPayFinalpaycode(refundOrderNo);
                newPay.setPayFinalpaytype(refundId);
                newPay.setPayStatusfinish("2");
                newPay.setPayUpdateBy(oldPatient.getUsername());
                newPay.setPayUpdateTime(new Date());
                payMapper.updateServicePay(newPay);
                ordersMapper.updateServiceOrders(newOrder);
                addOrderProcess(orderId);
            }else {
                return false;
            }


        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean notifyRefund(PatientOrderBody orderBody , LoginPatient oldPatient)
    {
        try {
            ServicePay newPay = new ServicePay();
            newPay.setPayId(orderBody.getOrderPay());
            newPay.setPayStatus("1");
            newPay.setPayStatusfinish("1");
            newPay.setPayUpdateBy(oldPatient.getUsername());
            newPay.setPayUpdateTime(new Date());
            payMapper.updateServicePay(newPay);

            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderBody.getOrderId());
            newOrder.setOrderPay(newPay.getPayId());
            newOrder.setOrderServiceflag(4);
            newOrder.setOrderFlag(2);
            //退款接口
            newOrder.setOrderFlag(3);
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());

            ordersMapper.updateServiceOrders(newOrder);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean modifyOrder(OrderModifyRequest orderBody , LoginPatient oldPatient)
    {
        try {
            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderBody.getOrderId());
            newOrder.setOrderServedid(orderBody.getServePersonId());
            ServiceServed served = servedMapper.selectServiceServedByServedId(orderBody.getServePersonId());
            newOrder.setOrderAddressid(served.getServedAddress());

            DateFormat cstFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = cstFormate.parse(orderBody.getServeTime());
            newOrder.setOrderScheduledtime(date);
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());

            ordersMapper.updateServiceOrders(newOrder);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public JSONObject payFinishOrder(Long orderId , LoginPatient oldPatient)
    {
        try {
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServicePay oldPay = payMapper.selectServicePayByPayId(order.getOrderPay());
            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());

            Long payroadDiff = payroad.getPayroadBill() + payroad.getPayroadActualpay() - payroad.getPayroadAdvancepay();
            Long payDiff = oldPay.getPayActualpay() - oldPay.getPayAdvancepay();
            Long totalDiff = payroadDiff + payDiff;

            String token_url = "https://hlwyy.ldqyylzx.cn/dhccam/token/generate?grant_type=api_credentials";

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", base64("a785cf74-de42-6905-2b2f-15ec02d376e9:34fb7fa64f43031419434c211ac48217"));

            Map<String, String> paramMap = new HashMap<>();
            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
            System.out.println(httpEntity);
            ResponseEntity<Object> response = restTemplate.postForEntity(token_url, httpEntity, Object.class);
            Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
            String token = (String) responseBody.get("access_token");

            String unifiedorder_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";


            Map<String, Object> data = new HashMap<String, Object>();

            data.put("tradeDesc", "HLHSSMFinalPay");
            data.put("orgId", "620000001222");
            data.put("tradeOrgCode", "JKL");
            data.put("shouldPay", ((float)(totalDiff) / 100) + "");
            data.put("total", ((float)(totalDiff) / 100) + "");
            data.put("coupon", "0");
            data.put("orgOrderNo", order.getOrderCode());
            data.put("openid", users.getUsersOpenid());

            data.put("orderType", "Other");
            data.put("useType", "wechatminipay");
            data.put("timestamp", Instant.now().getEpochSecond());
            String sign = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", data);
            data.put("sign", sign);


            Map<String, Object> stringObjectMap = buildMapHl( data, "paycenter.paygateway.unifiedorder", "body", token);

            headers = new HttpHeaders();
            headers.set("content-type", "application/json");

            HttpEntity<Map<String, Object>> httpEntityNew = new HttpEntity<>(stringObjectMap, headers);
            System.out.println(httpEntityNew);
            ResponseEntity<Object> orderPayInfo = restTemplate.postForEntity(unifiedorder_url, httpEntityNew, Object.class);

            Map<String, Object> orderPayInfoBody = (Map<String, Object>) orderPayInfo.getBody();
            String payCodeOld = (String) orderPayInfoBody.get("data");
            String payCode = AESUtils.Decrypt(payCodeOld);
            JSONObject jsonObject = new JSONObject(payCode);
            payCode = jsonObject.getString("orderNo");

            String gateway_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
            Map<String, Object> dataPay = new HashMap<String, Object>();
            dataPay.put("tradeDesc", "HLHSSMFinalPay");
            dataPay.put("orgId", "620000001222");
            dataPay.put("tradeOrgCode", "JKL");
            dataPay.put("shouldPay", ((float)(totalDiff) / 100) + "");
            dataPay.put("total", ((float)(totalDiff) / 100) + "");
            dataPay.put("coupon", "0");
            dataPay.put("orgOrderNo", order.getOrderCode());
            dataPay.put("openid", users.getUsersOpenid());

            dataPay.put("orderType", "Other");
            dataPay.put("regNo", users.getUsersId());
            dataPay.put("orderNo", payCode);
            dataPay.put("sourceCode", "7");
            dataPay.put("type", "Other");
            dataPay.put("useType", "wechatminipay");
            dataPay.put("timeStamp", Instant.now().getEpochSecond());
            String signPay = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", dataPay);
            dataPay.put("sign", signPay);


            Map<String, Object> payObjectMap = buildMapHl( dataPay, "paycenter.paygateway.gateway", "body", token);
            //unifiedEntity = new HttpEntity<>(stringObjectMap, headers);

            headers = new HttpHeaders();
            headers.set("content-type", "application/json");

            HttpEntity<Map<String, Object>> httpEntityPay = new HttpEntity<>(payObjectMap, headers);
            System.out.println(httpEntityPay);
            ResponseEntity<Object> appPayInfo = restTemplate.postForEntity(gateway_url, httpEntityPay, Object.class);

            Map<String, Object> appPayInfoBody = (Map<String, Object>) appPayInfo.getBody();
            String payDataOld = (String) appPayInfoBody.get("data");
            String payData = AESUtils.Decrypt(payDataOld);
            JSONObject appPayObject = new JSONObject(payData);



            ServicePay newPay = new ServicePay();
            //支付接口
            newPay.setPayId(order.getOrderPay());
            newPay.setPayFinalpay(oldPay.getPayActualpay());
            newPay.setPayFinalpaycode(payCode);
            newPay.setPayFinalpaytype("wxFinal");

            newPay.setPayActualpay(oldPay.getPayActualpay());
            newPay.setPayStatusfinish("0");
            newPay.setPayUpdateBy(oldPatient.getUsername());
            newPay.setPayUpdateTime(new Date());
            payMapper.updateServicePay(newPay);


            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderId);
            newOrder.setOrderServiceflag(14);
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());

            ordersMapper.updateServiceOrders(newOrder);
            addOrderProcess(orderId);

            return appPayObject;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public boolean notifyFinish(Long orderId, String transactionId)
    {
        try {
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServicePay oldPay = payMapper.selectServicePayByPayId(order.getOrderPay());
            ServiceUsers oldPatient = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());

            ServicePay newPay = new ServicePay();
            //支付接口
            newPay.setPayId(order.getOrderPay());
            newPay.setPayFinalpaytype(transactionId);
            newPay.setPayStatusfinish("0");
            newPay.setPayUpdateBy(oldPatient.getUsersName());
            newPay.setPayUpdateTime(new Date());
            payMapper.updateServicePay(newPay);

            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderId);
            newOrder.setOrderServiceflag(14);
            newOrder.setOrderUpdateBy(oldPatient.getUsersName());
            newOrder.setOrderUpdateTime(new Date());

            ordersMapper.updateServiceOrders(newOrder);
            addOrderProcess(orderId);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean assessOrder(PatientAssessReq assessBody , LoginPatient oldPatient)
    {
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(assessBody.getOrderId());
            ServiceAssessment newAssessment = new ServiceAssessment();
            ServiceOrders newOrder = new ServiceOrders();
            if(orders.getOrderAssessmentid() != null){
                newAssessment.setAssessmentId(orders.getOrderAssessmentid());
                String assessment = "";
                assessment = assessBody.getContent() + ":" + assessBody.getScore() + "⭐";
                newAssessment.setAssessmentUser(assessment);

                newAssessment.setAssessmentUserstatus("0");
                newAssessment.setAssessmentUpdateBy(oldPatient.getUsername());
                newAssessment.setAssessmentUpdateTime(new Date());
                assessmentMapper.updateServiceAssessment(newAssessment);
            }else{
                String assessment = "";
                assessment = assessBody.getContent() + ":" + assessBody.getScore() + "⭐";
                newAssessment.setAssessmentUser(assessment);
                newAssessment.setAssessmentUserstatus("0");
                newAssessment.setAssessmentCreateBy(oldPatient.getUsername());
                newAssessment.setAssessmentCreateTime(new Date());
                newAssessment.setAssessmentUpdateBy(oldPatient.getUsername());
                newAssessment.setAssessmentUpdateTime(new Date());
                assessmentMapper.insertServiceAssessment(newAssessment);
                newOrder.setOrderAssessmentid(newAssessment.getAssessmentId());
            }

            newOrder.setOrderId(assessBody.getOrderId());
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());
            ordersMapper.updateServiceOrders(newOrder);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean deleteOrder(Long orderId , LoginPatient oldPatient)
    {
        try {
            ServiceOrders newOrder = new ServiceOrders();
            newOrder.setOrderId(orderId);
            newOrder.setOrderUpdateBy(oldPatient.getUsername());
            newOrder.setOrderUpdateTime(new Date());

            newOrder.setOrderUseFlag("2");
            newOrder.setOrderDelFlag("2");

            ordersMapper.updateServiceOrders(newOrder);

        }catch (Exception e){
            return false;
        }
        return true;
    }


    @Transactional
    public boolean uploadMedical(PatientPictureRequest imagesInfo, LoginPatient oldPatient)
    {
        try {

            ServicePicture newPicture = new ServicePicture();
            newPicture.setPictureUserid(oldPatient.getUserId());
            newPicture.setPictureOrderid(imagesInfo.getOrderId());
            newPicture.setPictureType("0");//就医证明
            newPicture.setPictureCreateBy(oldPatient.getUsername());
            newPicture.setPictureCreateTime(new Date());
            newPicture.setPictureUpdateBy(oldPatient.getUsername());
            newPicture.setPictureUpdateTime(new Date());
            newPicture.setPictureRemark(imagesInfo.getRemark());
            for (String imageUrl : imagesInfo.getImgUrls()){
                newPicture.setPicturePic(imageUrl);
                pictureMapper.insertServicePicture(newPicture);
            }
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(imagesInfo.getOrderId());
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectOrderspackagesByOrderId(imagesInfo.getOrderId());
            List<ServicePicture> consumes = pictureMapper.selectConsumeListByOrderId(imagesInfo.getOrderId());
            if (orders.getOrderPay() != null){
                ServicePay payInfo = payMapper.selectServicePayByPayId(orders.getOrderPay());
                if("0".equals(payInfo.getPayStatus())){
                    orders.setOrderServiceflag(5);
                    orders.setOrderUseFlag("0");
                }else{
                    orders.setOrderServiceflag(3);
                    orders.setOrderUseFlag("1");
                }
                for (ServiceOrderspackages orderspackages : orderspackagesList) {
                    if(orderspackages.getOrderspackagesPackageid() == 0){
                        if (consumes == null){
                            orders.setOrderServiceflag(3);
                            orders.setOrderUseFlag("1");
                            break;
                        }
                    }
                }
                if (orders.getOrderServiceflag() == 5){
                    addOrderProcess(orders.getOrderId());
                }
            }

            ordersMapper.updateServiceOrders(orders);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean uploadConsume(PatientPictureRequest imagesInfo, LoginPatient oldPatient)
    {
        try {
            ServicePicture newPicture = new ServicePicture();
            newPicture.setPictureUserid(oldPatient.getUserId());
            newPicture.setPictureOrderid(imagesInfo.getOrderId());
            newPicture.setPictureType("1");//耗材证明
            newPicture.setPictureCreateBy(oldPatient.getUsername());
            newPicture.setPictureCreateTime(new Date());
            newPicture.setPictureUpdateBy(oldPatient.getUsername());
            newPicture.setPictureUpdateTime(new Date());
            newPicture.setPictureRemark(imagesInfo.getRemark());
            for (String imageUrl : imagesInfo.getImgUrls()){
                newPicture.setPicturePic(imageUrl);
                pictureMapper.insertServicePicture(newPicture);
            }

            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(imagesInfo.getOrderId());
            List<ServicePicture> medicals = pictureMapper.selectConsumeListByOrderId(imagesInfo.getOrderId());
            orders.setOrderServiceflag(3);
            orders.setOrderUseFlag("1");
            if (orders.getOrderPay() != null){
                ServicePay payInfo = payMapper.selectServicePayByPayId(orders.getOrderPay());
                if("0".equals(payInfo.getPayStatus())){
                    if (medicals != null){
                        orders.setOrderServiceflag(5);
                        orders.setOrderUseFlag("0");
                    }
                }else{
                    orders.setOrderServiceflag(3);
                    orders.setOrderUseFlag("1");
                }
                if (orders.getOrderServiceflag() == 5){
                    addOrderProcess(orders.getOrderId());
                }
            }

            ordersMapper.updateServiceOrders(orders);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean uploadHospital(PatientPictureBody pictureBody , LoginPatient oldPatient)
    {
        try {
            ServicePicture newPicture = new ServicePicture();
            newPicture.setPictureUserid(oldPatient.getUserId());
            newPicture.setPictureOrderid(pictureBody.getOrderId());
            newPicture.setPicturePic(pictureBody.getPicturePic());
            newPicture.setPictureType("0");//就医证明
            newPicture.setPictureCreateBy(oldPatient.getUsername());
            newPicture.setPictureCreateTime(new Date());
            newPicture.setPictureUpdateBy(oldPatient.getUsername());
            newPicture.setPictureUpdateTime(new Date());
            pictureMapper.insertServicePicture(newPicture);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean uploadSupplies(PatientPictureBody pictureBody , LoginPatient oldPatient)
    {
        try {
            ServicePicture newPicture = new ServicePicture();
            newPicture.setPictureUserid(oldPatient.getUserId());
            newPicture.setPictureOrderid(pictureBody.getOrderId());
            newPicture.setPicturePic(pictureBody.getPicturePic());
            newPicture.setPictureType("1");//耗材证明
            newPicture.setPictureCreateBy(oldPatient.getUsername());
            newPicture.setPictureCreateTime(new Date());
            newPicture.setPictureUpdateBy(oldPatient.getUsername());
            newPicture.setPictureUpdateTime(new Date());
            pictureMapper.insertServicePicture(newPicture);

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public List<PatientOrderTimeReturn> getOrderProcess(Long orderId,LoginPatient oldPatient){
        try {
            List<PatientOrderTimeReturn> timeReturnList = new ArrayList<PatientOrderTimeReturn>();
            List<ServiceTime> timeList = timeMapper.selectServiceTimeByOrderId(orderId);
            for (ServiceTime time : timeList) {
                PatientOrderTimeReturn orderTimeReturn = new PatientOrderTimeReturn();
                ServiceAction action = actionMapper.selectServiceActionByActionId(time.getTimeActionid());

                orderTimeReturn.setStatus(time.getTimeAction());
                DateFormat cstFormate = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                String timeInfo = cstFormate.format(time.getTimeTime());
                orderTimeReturn.setTime(timeInfo);
                orderTimeReturn.setDesc(action.getActionName());
                orderTimeReturn.setCurrent(false);
                timeReturnList.add(orderTimeReturn);
            }
            timeReturnList.get(timeReturnList.size()-1).setCurrent(true);
            return timeReturnList;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public Boolean addOrderProcess(Long orderId){
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServiceTime newTime = new ServiceTime();

            newTime.setTimeOrderid(orderId);
            newTime.setTimeTime(new Date());
            String process = "noNotify";

            Integer flag = orders.getOrderServiceflag();
            switch (flag){
                case 1:
                    newTime.setTimeAction("提交订单");
                    newTime.setTimeActionid(1L);
                    break;
                case 2:
                    newTime.setTimeAction("取消订单");
                    newTime.setTimeActionid(13L);
                    if (orders.getOrderPay() != null){
                        process = "订单取消";
                    }
                    break;
                case 3:
                    newTime.setTimeAction("支付订单");
                    newTime.setTimeActionid(2L);
                    break;
                case 4:
                    newTime.setTimeAction("订单退款/取消");
                    newTime.setTimeActionid(4L);
                    if (orders.getOrderPay() == null){
                        newTime.setTimeActionid(13L);
                        process = "订单取消";
                    }else{
                        process = "订单已退款";
                    }
                    break;
                case 5:
                    newTime.setTimeAction("护理部接单");
                    newTime.setTimeActionid(27L);
                    break;
                case 6:
                case 7:
                    newTime.setTimeAction("已分配");
                    newTime.setTimeActionid(23L);
                    process = "已分配护士";
                    break;
                case 8:
                    newTime.setTimeAction("待服务");
                    newTime.setTimeActionid(24L);
                    process = "护士已接单";
                    break;
                case 9:
                    newTime.setTimeAction("已出发");
                    newTime.setTimeActionid(9L);
                    process = "护士已出发";
                    break;
                case 10:
                    newTime.setTimeAction("服务中");
                    newTime.setTimeActionid(10L);
                    process = "护士已到达";
                    break;
                case 11:
                    newTime.setTimeAction("服务完成");
                    newTime.setTimeActionid(33L);
                    process = "服务完成";
                    break;
                case 12:
                    newTime.setTimeAction("费用核定");
                    newTime.setTimeActionid(30L);
                    break;
                case 13:
                    newTime.setTimeAction("用户确认");
                    newTime.setTimeActionid(35L);
                    break;
                case 14:
                    newTime.setTimeAction("最终支付");
                    newTime.setTimeActionid(36L);
                    process = "最终结算完成";
                    break;
                case 15:
                case 16:
                case 17:
                    newTime.setTimeAction("已完成");
                    newTime.setTimeActionid(37L);
                    process = "订单完成";
                    break;
            }

            if (timeMapper.insertServiceTime(newTime) == 1){
                if(orders.getOrderServiceflag() == 14){
                    newTime.setTimeAction("已完成");
                    newTime.setTimeActionid(37L);
                    timeMapper.insertServiceTime(newTime);
                }
                //return true;
            }
            if (process.equals("noNotify")){
                return true;
            }
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(orders.getOrderUserid());
            ServiceMsginfo msginfo = msginfoMapper.selectServiceMsginfoByMsg("订单状态");
            List<ServiceUsermsg> usermsgList = usermsgMapper.selectServiceUsermsgByUserId(orders.getOrderUserid());
            if (usermsgList == null) return true;
            Boolean notifyflag = false;
            for (ServiceUsermsg usermsg : usermsgList){
                if (usermsg.getUsermsgMsginfoid().equals(msginfo.getMsginfoId())){
                    if ("0".equals(usermsg.getUsermsgUseFlag())){
                        notifyflag = true;
                        break;
                    }else{
                        return true;
                    }
                }
            }
            if (!notifyflag) return true;

            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
            String retDesc = "";
            for (ServiceOrderscombo orderscombo : orderscomboList){
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                if (combo == null) continue;
                retDesc += combo.getComboName() + "(" + orderscombo.getOrderscomboCount() + "份);";
                break;
            }
            retDesc += "...";
            ServiceAppinfo appinfo = appinfoService.selectServiceAppinfoByAppinfoId(4L);

            // 获取token
            String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appinfo.getAppinfoAppid(), appinfo.getAppinfoSecret());
            com.alibaba.fastjson2.JSONObject tokenInfo = JSON.parseObject(HttpUtil.get(token_url));
            String accessToken = tokenInfo.getString("access_token");
            // 使用前端code获取手机号码 参数为json格式
            //String url = "https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("template_id", msginfo.getMsginfoValue());
            paramMap.put("page", "/pages/patOrder/patOrderDetail?orderId="+orderId);
            paramMap.put("touser", users.getUsersOpenid());

            Map<String, Object> data = new HashMap<>();
            Map<String, Object> thing5 = new HashMap<>();
            thing5.put("value", process);
            Map<String, Object> thing1 = new HashMap<>();
            thing1.put("value", retDesc);
            data.put("thing5", thing5);
            data.put("thing1", thing1);
            paramMap.put("data", data);
            paramMap.put("miniprogram_state", "developer");
            paramMap.put("lang", "zh_CN");
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            System.out.println(httpEntity);
            ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

            String body = String.valueOf(response.getBody());// 解析JSON字符串


        }catch (Exception e){
            return false;
        }
        return false;
    }

    @Transactional
    public Boolean addPayProcess(Long orderId, Long userId){
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(userId);
            ServiceTime newTime = new ServiceTime();
            newTime.setTimeOrderid(orderId);
            newTime.setTimeTime(new Date());

            if(orders.getOrderServiceflag() >= 14){
                newTime.setTimeAction("已完成");
                newTime.setTimeActionid(37L);
            }else{
                newTime.setTimeAction("订单支付");
                newTime.setTimeActionid(2L);

            }
            timeMapper.insertServiceTime(newTime);

            ServiceMsginfo msginfo = msginfoMapper.selectServiceMsginfoByMsg("订单已支付通知");
            List<ServiceUsermsg> usermsgList = usermsgMapper.selectServiceUsermsgByUserId(orders.getOrderUserid());
            if (usermsgList == null) return true;
            Boolean notifyflag = false;
            for (ServiceUsermsg usermsg : usermsgList){
                if (usermsg.getUsermsgMsginfoid().equals(msginfo.getMsginfoId())){
                    if ("0".equals(usermsg.getUsermsgUseFlag())){
                        notifyflag = true;
                        break;
                    }else{
                        return true;
                    }
                }
            }
            if (!notifyflag) return true;

            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
            String retDesc = "";
            for (ServiceOrderscombo orderscombo : orderscomboList){
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                if (combo == null) continue;
                retDesc += combo.getComboName() + "(" + orderscombo.getOrderscomboCount() + "份);";
                break;
            }
            retDesc += "...";
            ServiceAppinfo appinfo = appinfoService.selectServiceAppinfoByAppinfoId(4L);

            // 获取token
            String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appinfo.getAppinfoAppid(), appinfo.getAppinfoSecret());
            com.alibaba.fastjson2.JSONObject tokenInfo = JSON.parseObject(HttpUtil.get(token_url));
            String accessToken = tokenInfo.getString("access_token");
            // 使用前端code获取手机号码 参数为json格式
            //String url = "https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("template_id", msginfo.getMsginfoValue());
            paramMap.put("page", "/pages/patOrder/patOrderDetail?orderId="+orderId);
            paramMap.put("touser", users.getUsersOpenid());

            Map<String, Object> data = new HashMap<>();
            Map<String, Object> thing5 = new HashMap<>();
            thing5.put("value", "订单已支付");
            Map<String, Object> thing1 = new HashMap<>();
            thing1.put("value", retDesc);
            data.put("thing5", thing5);
            data.put("thing1", thing1);
            paramMap.put("data", data);
            paramMap.put("miniprogram_state", "developer");
            paramMap.put("lang", "zh_CN");
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            System.out.println(httpEntity);
            ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

            String body = String.valueOf(response.getBody());// 解析JSON字符串

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public refundRspTemp getOrderCancelReason(Long orderId, LoginPatient oldPatient){
        try {
            List<ServiceCancelorderreason> reasonList = cancelorderreasonMapper.selectServiceCancelorderreasonListAll(new ServiceCancelorderreason());
            List<Map<String,Object>> reasonReturnList = new ArrayList<Map<String,Object>>();
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            for (ServiceCancelorderreason reason : reasonList) {
                Map<String,Object> reasonMap = new HashMap<String,Object>();
                reasonMap.put("id",reason.getCancelorderreasonId());
                reasonMap.put("name",reason.getCancelorderreasonName());
                reasonReturnList.add(reasonMap);
            }
            refundRspTemp refundRspTemp = new refundRspTemp();
            refundRspTemp.setCategories(reasonReturnList);

            if (orders.getOrderPay() != null){
                ServicePay pay = payMapper.selectServicePayByPayId(orders.getOrderPay());
                ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);

                CurrentCancelInfo currentCancelInfo = new CurrentCancelInfo();
                currentCancelInfo.setCancelspecAmount(pay.getPayAdvancepay());
                currentCancelInfo.setCancelTaxiAmount(payroad.getPayroadAdvancepay());
                currentCancelInfo.setCancelTotalAmount(pay.getPayAdvancepay() + payroad.getPayroadAdvancepay());
                refundRspTemp.setCurrentCancelInfo(currentCancelInfo);
            }

            List<String> cancelDesc = new ArrayList<String>();
            cancelDesc.add("订单一旦取消，将无法恢复");
            cancelDesc.add("退款将预计1-3个工作日原路返回到支付账户");
            cancelDesc.add("护士已出发的订单，将会扣除预付服务费的30%，若护士已抵达并开展服务，将会扣除预付服务费的60%，以及预估的车程费用，剩余款项将原路退还到您的支付账户，详情请查看退款进度");
            refundRspTemp.setCancelDesc(cancelDesc);

            return refundRspTemp;
        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public Boolean deleteFile(Long orderId, String fileUrl, LoginPatient oldPatient){
        try {
            ServicePicture searchPicture = new ServicePicture();
            searchPicture.setPictureOrderid(orderId);
            searchPicture.setPictureUserid(oldPatient.getUserId());
            searchPicture.setPicturePic(fileUrl);
            List<ServicePicture> pictures = pictureMapper.selectServicePictureList(searchPicture);
            if (pictures.size() == 0){
                return false;
            }
            File file = new File(fileUrl);
            if (file.delete()) {
                searchPicture.setPictureId(pictures.get(0).getPictureId());
                searchPicture.setPictureUseFlag("2");
                searchPicture.setPictureDelFlag("2");
                pictureMapper.updateServicePicture(searchPicture);
                return true;
            } else {
                return false;
            }

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public Boolean saveNotify(List<Map<String, Object>> templates, LoginPatient oldPatient){
        try {
            usermsgMapper.deleteServiceUsermsgByUserId(oldPatient.getUserId());

            for (Map<String, Object> template : templates) {
                List<ServiceMsginfo> msginfoList = msginfoMapper.selectServiceMsginfoByValue(template.get("value").toString());
                for (ServiceMsginfo msginfo : msginfoList) {
                    if (msginfo != null){
                        ServiceUsermsg usermsg = new ServiceUsermsg();
                        usermsg.setUsermsgUserid(oldPatient.getUserId());
                        usermsg.setUsermsgMsginfoid(msginfo.getMsginfoId());
                        usermsg.setUsermsgCreateBy(oldPatient.getUserId().toString());
                        usermsg.setUsermsgCreateTime(new Date());
                        usermsg.setUsermsgUpdateBy(oldPatient.getUser().getUsersOpenid().toString());
                        usermsg.setUsermsgUpdateTime(new Date());
                        if (template.get("flag") != null){
                            String flag = template.get("flag").toString().equals("true") ? "0" : "2";
                            usermsg.setUsermsgUseFlag(flag);
                            usermsg.setUsermsgDelFlag(flag);
                        }
                        usermsgMapper.insertServiceUsermsg(usermsg);
                    }
                }
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

}
